我有一个宠物的模型,它看起来像
class Pet(models.Model):
STATUS_CHOICES=(
(1,'Listed for sale'),
(2,'Dead'),
(3,'Sold'),
)
name = models.CharField(_("name"), max_length=50 )
species = models.ForeignKey(PetSpecies, related_name = "pets")
pet_category = models.ForeignKey(PetCategory, related_name = "pets")
pet_type = models.ForeignKey(PetType, related_name = "pets")
# want to add dynamic fields here depends on above select options(species, category, type)
color = models.CharField(_("color"), max_length=50, null=True, blank=True)
weight = models.CharField(_("weight"), max_length=50, null=True, blank=True)我已经读过Dynamic Models了,它对我有帮助吗?或者我应该做一些其他的事情?如果有人知道,请指导我与一段代码。
谢谢:)
发布于 2011-04-18 17:13:43
实际上,你分享的链接并不是你需要的.
你需要的是一个数据库表结构,它可以存储不同类型的定义和相关记录……在这一点上,您可能需要更改数据库表结构...
首先,您可以定义一个存储类别标签的表,如下所示
class PetTyper(models.Model):
specy = models.ForeignKey(...)
category = models.ForeignKey(...)
type = models.Foreignkey(...)
...
additional_fields= models.ManyToManyField(AdditionalFields)
class AdditionalFields(Models.Model):
label = models.CharField(_("Field Label")PetTyper是宠物类型的基本记录表,因此您将在此表中定义每个宠物,附加字段将显示每个记录中将显示的额外字段。不要忘记,这些表将记录基本类型和附加结构,而不是添加的动物的记录。
因此,这样的记录可能包含以下信息:
pettYpe:哺乳动物,狗,拉布拉多猎犬,additional_info =颜色,重量
它告诉你,任何记录为LAbrador Retreiver的狗都会有颜色和体重信息...
对于记录到数据库中的每个拉布拉多猎犬,都会将数据记录到以下表格中:
class Pet(models.Model):
name = models.CharField(...)
typer = models.ForeignKey(PetTyper) # this will hold records of type, so no need for specy, category and type info in this table
... # and other related fields
class petSpecifications(models.Model):
pet = Models.ForeignKey(Pet) # that data belongs to which pet record
extra_data_type = Models.ForeignKey(AdditionalFields) # get the label of the extra data field name
value = models.CharField(...) # what is that extra info value因此,当您创建一个新的宠物条目时,您将定义一个petTyper,并向AdditionalFields添加每个附加字段数据的名称。在您的新宠物记录表单中,您将首先获取宠物类型,然后从AdditionalFields表中获取每个附加信息数据。用户将输入宠物的名字后,他/她选择类型,然后添加颜色和重量信息(从上面的示例)。您将从表单中获取这些信息,并在pet表上创建一条记录,然后将有关该记录的每个特定信息添加到petSpecifications表中……
这种方法相当困难,而且你不能使用一些基本的django特性,比如表单、表单模型等等,因为你需要从PetTyper和AdditionalFields表中读取数据,然后通过这些信息来创建表单。并将发布的信息记录到Pet和petSpecifications表中。
https://stackoverflow.com/questions/5699805
复制相似问题