Reputation: 509
I am new to Django and trying to understand the model relationships, here is my use case:
I have a Creator
object which can create multiple Listing
under a Category
. Category
can have multiple Listing
s from multiple Creator
s.
Creator -- Creates a Listing about a service -- under a Category or multiple Category
I am trying to find the thought process behind picking the correct relationship while defining this kind circular relationship. Which one of the model should go first? Is it Category which is first and Creator second and Listing at the end, is Creator, Category and Listing all belong to a Many to Many relationship, if then how are they linked?
Upvotes: 1
Views: 265
Reputation: 521
In Django Models there are three types of relationships.
one to one - when one entity is unique to other entity Example: A user model can be in one to one relationship to customer model. Every customer is unique user
many to many - When one entity can has relationship with many other entities and vice versa. Example : pizza and toppings, pizza can have many toppings, and same topping can be applied on various pizza
one to many - also called foreign key in Django when a single entity is related to many other entities but vice versa is not true.
Example: your Use case applies here. A creator can create multiple listings but a single listing can be mapped to single creator only, not multiple creator.
Upvotes: -1
Reputation: 59164
You don't have a circular relationship, this should cover your use case:
class Creator:
...
class Category:
...
class Listing:
creator = models.ForeignKey(Creator, on_delete=models.PROTECT)
category = models.ManyToMany(Category)
I am assuming that a Listing
can be under multiple Category
s. If each listing can only have one Category
, the second (category
) relation must be a ForeignKey
too.
Upvotes: 2