Golden Codes - armanexplorer planet

Practical code snippets for Django, Python, Bash, Git and All!

View on GitHub

Docs

many-to-one (Foreign Key)

From Many (source of the relationship) to One (target)

Cardinality: many instances of source participate in the relationship with a single instance of destination

it’s suggested, but not required, that the name of a ForeignKey field (manufacturer in the example above) be the name of the model, lowercase.

Base Examples

many-to-many

Generally, ManyToManyField instances should go in the object that’s going to be edited on a form. In the above example, toppings is in Pizza (rather than Topping having a pizzas ManyToManyField ) because it’s more natural to think about a pizza having toppings than a topping being on multiple pizzas. The way it’s set up above, the Pizza form would let users select the toppings.

Base Examples

many-to-many with extra fields

one-to-one

Base Examples

one-to-many

Django doesn't explicitly define a One-to-Many relationship. However, it arises naturally from the Many-to-One relationship.

One-to-Many is implicit and accessed through the related manager, e.g., comment_set in the example of Blog and Comment relation

The related_name argument in the ForeignKey field can be used to customize the name of the related manager.