Django models with variable number of fields

前端 未结 2 1487
[愿得一人]
[愿得一人] 2021-01-13 22:40

I\'m working on a new project and I\'d like to create a django model that will have a variable number of EmailFields depending on another variable. What I\'m tr

相关标签:
2条回答
  • 2021-01-13 23:26

    Because Django's model fields are directly linked to fields in a table in the database, a variable number of fields isn't possible. Instead, have another table with a foreign key:

    class House(models.Model):
        # normal house fields go here
    
    class EmailAddress(models.Model):
        email = models.EmailField()
        house = models.ForeignKey(House, related_name='email_addresses')
    

    Now you can access all the emails related to a house by using:

    house = House.objects.get(pk=1)
    house.email_addresses.all()
    

    The ForeignKey documentation might be useful.

    0 讨论(0)
  • 2021-01-13 23:28

    No. Put the emails in a separate model and link them back to House with a ForeignKey.

    0 讨论(0)
提交回复
热议问题