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)
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.
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With