我正在尝试创建一个系统,以使用户可以对其他用户发表评论。因此,我使用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)
答案 0 :(得分:2)
尝试在User
中以字符串形式引用ForeignKey
模型,如下所示:
author = models.ForeignKey(
'app1.User',
on_delete=models.CASCADE,
related_name='wrote')
)
此外,还要删除from app1.models import User
。