[Fixed]-How can I define a polymorphic relation between models in Django?

6👍

ContentTypes is the right approach.
This is because the ForignKey can only point to one type of table so you need to pass through the an intermediate table and do your split depending on the different type.

So model inheritance for the class hierarchy, but ContentType for the foreign keys.

👤ivan

3👍

If you only need to point to “any product,” not any model, then the solution is to have a Product model that all products inherit from (i.e. Television and Camcorder are both subclasses of Product), and give your Offer model a ForeignKey to Product.

3👍

You can’t do that in Django. Either use generic relations or a Django app that add this feature like django_polymorphic.

2👍

Take a look at django-polymorphic, this implements this feature, and also uses ContentTypes internally.

👤vdboor

-4👍

You might want to have a look at model inheritance.

Leave a comment