多对一关系
fromdjango.dbimport models class Author(models.Model): name = models.CharField(max_length=50) #Book has a foreignkey (many to one) relationship with author class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) publish_date = models.DateField()
最通用的选项。可以在您想要代表任何关系的任何地方使用
多对多关系
class Topping(models.Model): name = models.CharField(max_length=50) # One pizza can have many toppings and same topping can be on many pizzas class Pizza(models.Model): name = models.CharField(max_length=50) toppings = models.ManyToManyField(Topping)
在内部,这是通过另一个表表示的。并ManyToManyField应放在将在表单上进行编辑的模型上。例如:Appointment将具有ManyToManyField被叫Customer,Pizza具有Toppings等等。
使用直通类的多对多关系
class Service(models.Model): name = models.CharField(max_length=35) class Client(models.Model): name = models.CharField(max_length=35) age = models.IntegerField() services = models.ManyToManyField(Service, through='Subscription') class Subscription(models.Model): client = models.ForeignKey(Client) service = models.ForeignKey(Service) subscription_type = models.CharField(max_length=1, choices=SUBSCRIPTION_TYPES) created_at = models.DateTimeField(default=timezone.now)
这样,我们实际上可以保留有关两个实体之间关系的更多元数据。可以看出,客户端可以通过几种订阅类型订阅几种服务。在这种情况下的唯一区别是,要向M2M关系中添加新实例,不能使用捷径方法,而应创建直通类的新对象,pizza.toppings.add(topping)Subscription.objects.create(client=client, service=service, subscription_type='p')
在其他语言through tables中,也称为JoinColumn,Intersection table或mapping table
一对一关系
class Employee(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() spouse = models.OneToOneField(Spouse)class Spouse(models.Model): name = models.CharField(max_length=50)
当两个模型之间只有合成关系时,请使用这些字段。