更新时间:2023-12-02 21:26:16
您以相反的方式创建关系;将外键添加到 Person
类型以创建多对一关系:
You create the relationships the other way around; add foreign keys to the Person
type to create a Many-to-One relationship:
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
anniversary = models.ForeignKey(
Anniversary, on_delete=models.CASCADE)
address = models.ForeignKey(
Address, on_delete=models.CASCADE)
class Address(models.Model):
line1 = models.CharField(max_length=150)
line2 = models.CharField(max_length=150)
postalcode = models.CharField(max_length=10)
city = models.CharField(max_length=150)
country = models.CharField(max_length=150)
class Anniversary(models.Model):
date = models.DateField()
任何一个人只能连接到一个地址和一个周年纪念,但地址和周年纪念可以从多个Person
条目中引用.
Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person
entries.
Anniversary
和 Address
对象也将被赋予反向、向后的关系;默认情况下,它会被称为 person_set
但如果需要,您可以配置不同的名称.请参阅以下关系向后"查询文档.
Anniversary
and Address
objects will be given a reverse, backwards relationship too; by default it'll be called person_set
but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.