Django GenericRelation递归导入

时间:2018-08-02 18:24:18

标签: python django python-3.x django-models

我正在尝试创建一个系统,以使用户可以对其他用户发表评论。因此,我使用GenericRelation创建了一个模型,如下所示:

App1 \ models.py:

from django.contrib.auth.models import AbstractUser
from django.contrib.contenttypes.fields import GenericRelation

from app2.models import Social

class User(AbstractUser):
    """
    Default User model used for authentification system
    """

    relation = GenericRelation(Social)    # recently added

App2 \ models.py:

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

from app1.models import User

class Social(models.Model):
    content_object = GenericForeignKey('content_type', 'object_id')
    object_id = models.PositiveIntegerField()

    content_type = models.ForeignKey(ContentType,
                                     on_delete=models.CASCADE)

    author= models.ForeignKey(User,  # Member who wrote the message
                             on_delete=models.CASCADE,
                             related_name='wrote')
    message= models.TextField()

relation中添加字段User之前。我没有任何问题,但我正在重做GenericRelation的工作,我想简化我的鳕鱼。

然后当我运行服务器时出现问题。我处于递归导入循环中...

file .\app2\models.py
  from app2.models import Social
file .\app1\models.py
  from app1.models import User

是否可以通过在我的GenericRelation上保留一个GenericRelation的社交名额和User来解决此问题? 因为之后我想在其他模型/

上添加其他GenericRelation(Social)

1 个答案:

答案 0 :(得分:2)

尝试在User中以字符串形式引用ForeignKey模型,如下所示:

author = models.ForeignKey(
    'app1.User',
    on_delete=models.CASCADE,
    related_name='wrote')
)

此外,还要删除from app1.models import User