2014-09-19 51 views
-1

的型号:的ModelForm ForeignKey的用在继承的模型

class Human(models.Model): 
    UNIQUE = models.CharField(max_length=10) 
    name = models.CharField(max_length=30) 
    father = models.ForeignKey('Human', null=True, blank=True) 
    mother = models.ForeignKey('Human', null=True, blank=True) 

class Person(Human): 
    email = models.EmailField() 

而现在,我试图做的ModelForm:

class PersonForm(ModelForm): 
    class Meta: 
    model = Person 
    fields = ('UNIQUE','name','email') 

截止本 - 完美的作品。

,现在我想补充两个字段:父亲和母亲

如果个人已经拥有的父亲(和/或母亲) - 只显示名称。如果不是 - 显示字段(或两个字段),用户必须输入UNIQUE。

我堆在刚刚加场:我尝试爸爸妈妈加入到类元字段:

class PersonForm(ModelForm): 
    class Meta: 
    model = Person 
    fields = ('UNIQUE','name', 'email', 'father', 'mother') 

错误说:

Exception Type: AttributeError 
Exception Value: 'Person' object has no attribute 'father_id' 

这是不正确的,因为它有这个属性(从人类继承)....任何提示?

大部分的解决方案分进入choiceview,但我不希望显示的可能性 - 只要输入唯一的,如果是在基地 - 显示,如果不是 - 什么都不做

编辑

因为讨论错误的方式 - 模型人类和模型人肯定是好的 - 在管理一切正常 - 但我创建了输入数据的界面(我不想从管理模块等其他可能性中选择父/母)

编辑ED2 非常重要的修改:

father = models.ForeignKey('Human', related_name="father", null=True, blank=True) 
    mother = models.ForeignKey('Human', related_name="mother", null=True, blank=True) 

错误消失,并在形式出现的母亲/父亲的ID - 这是非常接近它变成UNIQUE

+0

'father = models.ForeignKey,null = True,blank = True)' - 非常奇怪的行。它确切的代码? – stalk 2014-09-19 09:00:54

+0

对不起,我的错误 - 当然不是...... – 2014-09-19 09:20:36

+0

你为什么在'ModelForm'中'model = Person'而不是'model = Human'?错误地告诉,发生了什么:人模型没有'父'字段 – stalk 2014-09-19 09:26:57

回答

0

的问题是这是作为字段名 - 这导致错误相同related_names ..

这是正确答案: father = models.ForeignKey('Human',related_name =“fathers_children”,null = True,blank = True) mother = models.ForeignKey('Human',related_name =“mothers_children”,null = True,空白= True)

1

为了避免意见,我广泛的讨论在这里放一个可能的答案。 数据库中是否有两个表personhuman? 类PersonHuman继承,从而递归关系。如果表human不在数据库中,则建立关系的类Person的所有尝试都是徒劳的。

编辑:

因此,让我们总结一下吧,因为它似乎是相关名称是造成问题的原因。 当从一个模型创建多个外键(或递归关系本身)时,您需要指定不同的相关名称。如果未指定,则Django会尝试通过将_set附加到模型名称来创建相关名称。 在你的情况下,它会像person.human_set.all()person是类Person的实例)。在这里,父母之间无法区分。 有还宣布了相关的名称作为+禁用落后关系的可能性: related_name='+'

+0

当然是都在数据库中。 Person具有指向人员ID的email和human_ptr_id。 – 2014-09-19 10:45:00

+0

'human_ptr_id'从哪里来?错误消息说'Person'没有属性'father_id'。 Django附加'_id'来查找相关模型的主键。 “人”这个表必须有一个主键。数据库中该列的名称是什么? – cezar 2014-09-19 10:54:26

+0

Django本身创建数据库。我在数据库中没有任何修改人的主键当然是id。 – 2014-09-19 10:57:58