[Python] Wagtail one-to-one object hierarchy with enum type field

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I have a wagtail site and I want to create an object hierarchy in a one-to-one matter, but with multiple options. Basically, I want that the database setup look slike this:

    CREATE TABLE products (
    id PRIMARY KEY,
    product_type VARCHAR(10) CHECK (product_type IN ('BOOK', 'SHIRT', ...)),
    product_name VARCHAR(255),
    product_description TEXT,
    ...
    );
    CREATE TABLE product_shirts (
    id PRIMARY KEY,
    product_id integer REFERENCES products (id),
    size varchar(255),
    ...
    );
    CREATE TABLE product_books (
    id PRIMARY KEY,
    product_id integer REFERENCES products (id),
    author varchar(255),
    ...
    );


    It is pretty straigt forward to create a regular one-to-one relationship with setting ParentalKey in the derived model. However, I want to also have an enum-type field in the parent model to check which product type we have, so that I can do something like that in my ProductsView:

    if object.product_type == 'SHIRT':
    # display additional shirt attributes
    elif object.product_type == 'BOOK':
    # display book attributes
    else:
    # unknown type, should not happen


    I know, that with a one-to-one relationship in wagtail I could just simply call product.shirtwhich would raise an exception, if the product is not a shirt. But it seems very cumbersome to have nested try-catch blocks if I have many different product types...

    Any better idea to solve this in a django/wagtail style?

    Continue reading...

Compartilhe esta Página