继承模型中具有外键的ModelForm

时间:2014-09-19 08:53:44

标签: django foreign-keys django-forms

模特:

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')

直到这个 - 工作完美。

现在我想添加两个字段:父亲和母亲

如果Person已经拥有父亲(和/或母亲) - 只需显示姓名。如果不是 - 显示字段(或两个字段),用户必须键入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,但我不想展示可能性 - 只要输入UNIQUE,如果它是在base - show中,如果不是 - 什么都不做

编辑

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

edited2 非常重要的修改:

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

错误消失了,并且在表单中显示了母亲/父亲的ID - 它非常接近将其更改为UNIQUE

2 个答案:

答案 0 :(得分:1)

为避免在评论中进行扩展讨论,我在这里提出了一个可能的答案。 您是否在数据库中同时拥有表personhuman? 类Person继承自Human,因此继承了递归关系。如果表human不在数据库中,那么类Person的所有尝试都无法建立关系。

编辑:

因此,让我们总结一下,因为似乎相关名称导致了问题。 当从一个模型到另一个模型创建多个外键(或者作为递归关系自身)时,需要指定不同的相关名称。如果未指定,Django会尝试通过将_set附加到模型名称来创建相关名称。 在您的情况下,它类似于person.human_set.all()person是类Person的实例)。在这里,它可以区分父亲和母亲。 通过将相关名称声明为+,还可以禁用向后关系: related_name='+'

答案 1 :(得分: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,blank = True)