如果不导入相关模型本身,相关对象引用将不起作用

时间:2018-05-22 19:12:08

标签: django django-models django-rest-framework django-rest-viewsets

我的应用程序中有2个模型 -

在models / parent.py中我有 -

 from django.db import models
 class Parent(models.Model): 
       class Meta:
          db_table = "parent_table"
       start_date = models.DateField()
       end_date = models.DateField()

在models / child.py中我有 -

from django.db import models
from models.parent import Parent
class Child(models.Model): 
   class Meta:
      db_table = "child_table"
   some_ref = models.ForeignField(Parent)

现在在models / parent.py中我将属性定义为 -

@property
def referred_values(self):
 return self.child_set.all()

它给了我错误 -

AttributeError: 'Parent' object has no attribute 'child_set'

但是如果我在我的应用程序中的任何文件中导入Child类,它都可以正常工作。 这是预期的行为,还是我在这里遗漏了什么?

提前致谢。

1 个答案:

答案 0 :(得分:2)

最好直接设置related_name

some_ref = models.ForeignField(Parent, related_name='childs')

并使用child_set的儿童(更多英语)

您也可以使用:

 some_ref = models.ForeignField(to='parent_app.Parent', related_name='childs')

并且您不需要导入Parent to Child模型

此外:

class Parent(models.Model): 

insted of

 class Parent:

但是在你的问题中,我认为你忘了将Child添加到models / __ init __。py