Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a polymorphic relation between models in Django?

I am working on a Django application which contains an Offer model. An Offer instance contains the pricing conditions and points to a product definition. The product model is actually a hierarchy (I have a Television model, a Camcorder model, etc.). So I would like the Offer model to contain a polymorphic (or "generic") association to point to any product.

For now, all I have found is this to use the generic associations in the ContentTypes application. This might do, but I am looking for alternatives, if any.

Thanks for your help.

(one solution per answer please)

like image 239
MiniQuark Avatar asked Jan 06 '09 10:01

MiniQuark


People also ask

What is polymorphic model in Django?

A polymorphic model is used when a single entity requires different functionality or information. In the examples above, all events are logged for future use, but they can contain different data. All users need be able to log in, but they might have different profile structures.

How do I create a one to many relationship in Django?

To handle One-To-Many relationships in Django you need to use ForeignKey . The current structure in your example allows each Dude to have one number, and each number to belong to multiple Dudes (same with Business).

What is __ Str__ in Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this. Note: how objects are just plainly numbered. to this.

How will you define the model classes in Django?

When you make a model class in Django, consider that class the data-table, each individual instance of that class the table rows, and the attributes(e.g: title) of each table the columns. In the definition of the class Book, title seems to be a class attribute.


2 Answers

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.

like image 150
ivan Avatar answered Oct 01 '22 18:10

ivan


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.

like image 38
Carl Meyer Avatar answered Oct 01 '22 18:10

Carl Meyer