Django models with variable number of fields

戏子无情 提交于 2019-12-12 17:12:53

问题


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 trying to create is a House model that has all the members of the house in it (more specifically, their email addresses). Seeing as not all houses are the same size some will have more members than others.

I'd like the user to enter the number of members in their house and have django create an according number of EmailFields on the model. Is there any easy way to accomplish this? Thanks.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/18291244/django-models-with-variable-number-of-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!