0

我的应用中有 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 类,它就可以正常工作。这是预期的行为还是我在这里遗漏了什么?

提前致谢。

4

1 回答 1

3

直接设置related_name就好了

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

并使用 childs insted of child_set(更多英文)

您也可以使用:

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

而且您不需要将父模型导入子模型

还:

class Parent(models.Model): 

安装的

 class Parent:

但是在您的问题中,我认为您忘记将 Child 添加到 models/__init__.py

于 2018-05-22T19:21:53.840 回答