[Answer]-How to create django database model that "knows" what kind of category it is?

1đź‘Ť

âś…

According to the docs on multi-table inheritance you can reference the lowercase name of the model. In your case to find out the “product type” you’d do something like:

product = Product.objects.get(id=12)
try:
    mattress = product.mattress
    is_mattress = True
except Mattress.DoesNotExist:
    is_mattress = False

You could abstract this out to a helper method that would do the tests for you and return the type as a string or enum of some sort.

👤mVChr

0đź‘Ť

If you have a reference to an object, can’t you use something like:

p = Product.objects.get(id=1)

class_of_p = str(p.__class__)

and then parse the resulting string

"<class 'whatever.models.Pillow'>"

to find what you need? Apologies if I’m missing something.

👤LAK

Leave a comment