You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Manufacturer(models.Model):
# ...
pass
class Car(models.Model):
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
Many to Many
Pizza has multiple Topping and Topping can be on multiple pizzas
it doesn't matter which model has the m2mfield but should only put it on one not both
plural lowercase of class toppings
you can also create recursive relationships
class Topping(models.Model):
# ...
pass
class Pizza(models.Model):
# ...
toppings = models.ManyToManyField(Topping)
intermediary
you explicitly specify foreign keys to the models that are involved in the many-to-many relationship
intermediate model must contain one - and only one - foreign key to the source model
For a model which has a many-to-many relationship to itself through an intermediary model, two foreign keys to the same model are permitted, but they will be treated as the two (different) sides of the many-to-many relationship
defining a many-to-many relationship from a model to itself, using an intermediary model, you must use symmetrical=False
beatles.members. add() or create() or set() to create relationships with through_default={dict}
remove() or clear()
class Person(models.Model):
name = models.CharField(max_length=128)
def __str__(self):
return self.name
class Group(models.Model):
name = models.CharField(max_length=128)
# through
members = models.ManyToManyField(Person, through='Membership')
def __str__(self):
return self.name
# intermediary
class Membership(models.Model):
# fk to models that are involved to m2m how to models are related
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
date_joined = models.DateField()
Group.objects.filter(members__name
Person.objects.filter(
group__name='The Beatles',
membership__date_joined
# need to access a membership’s information you may do
Membership.objects.get(group=beatles, person=ringo)
# access the same information is by querying the many-to-many reverse relationship from a Person object:
ringo.membership_set.get(group=beatles)
One-to-one
This is most useful on the primary key of an object when that object “extends” another object in some way.
palces to resturant by inheritance because resturant is a place
parent_link
Field name restrictions
python reserved, dunder, end with underscore
Meta anything that's not a field
Manager. It’s the interface through which database query operations are provided to Django models and is used to retrieve the instances from the database.