具有可变数量字段的Django模型 [英] Django models with variable number of fields

查看:201
本文介绍了具有可变数量字段的Django模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个新项目,我想创建一个django模型,根据另一个变量,它将有一个变量数量 EmailField 。我想要创建的是一个房子模型,其中包含房子的所有成员(更具体地说是他们的电子邮件地址)。看到并不是所有的房子是相同的大小一些会有比其他人更多的成员。



我希望用户输入他们家中的会员数量,并且django会创建一个相对数量的 EmailField s模型。有没有办法完成这个?谢谢。

解决方案

由于Django的模型字段直接链接到数据库中的表中的字段,所以可变数量的字段isn'可能。相反,有另一个表与外键:

  class House(models.Model):


class EmailAddress(models.Model):
email = models.EmailField()
house = models.ForeignKey(House,related_name ='email_addresses')

现在您可以使用以下方式访问与房屋有关的所有电子邮件:

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

ForeignKey 文档可能很有用。


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.

解决方案

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.

这篇关于具有可变数量字段的Django模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆