Foreign Key Django Model

后端 未结 2 623
情书的邮戳
情书的邮戳 2020-12-07 10:36

I\'m trying to create 3 models ; Person, Address and Anniversy. The plan is to have one address and one anniversy for each person. But

相关标签:
2条回答
  • 2020-12-07 10:58

    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()
    

    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 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.

    0 讨论(0)
  • 2020-12-07 11:13

    I would advise, it is slightly better practise to use string model references for ForeignKey relationships if utilising an app based approach to seperation of logical concerns .

    So, expanding on Martijn Pieters' answer:

    class Person(models.Model):
        name = models.CharField(max_length=50)
        birthday = models.DateField()
        anniversary = models.ForeignKey(
            'app_label.Anniversary', on_delete=models.CASCADE)
        address = models.ForeignKey(
            'app_label.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()
    
    0 讨论(0)
提交回复
热议问题