【问题标题】:Circular reference in Django model?Django模型中的循环引用?
【发布时间】:2015-10-28 23:32:48
【问题描述】:

我想创建两个模型:1) 对话,它存储对带有标题的根消息的引用和 2) 消息,它存储消息的内容/文本和对活动的引用。该计划是链接消息并最终创建一个对话树。对话中的根消息将充当链接消息网络的头(入口)节点。

以下是我在模型文件中定义的内容(分别为conversations/models.pymessages/models.py):

from messages.models import Message
class Conversation(models.Model):
    title = models.CharField('Conversation Title', max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)
    composer = models.ForeignKey(User)
    root_message =  models.ForeignKey(Message, null=True, blank=True)

from conversations.models import Conversation
class Message(models.Model):
(foreignkey very likely)
    conversation = models.ForeignKey(Conversation, null=True, blank=True)
    content = models.TextField(db_index=True, max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)

问题是当我运行南的schemamigration messages --autoschemamigration conversations --auto 时,我遇到了这样的错误:

    class Campaign(models.Model):
  File "C:\Users\Documents\GitHub\t4s\conversations\models.py", line 11, in Conversation
    from messages.models import Message
ImportError: cannot import name Message

我相信这是因为 MessageConversation 正在相互导入。但我希望每个Message 实例与Conversation 有关联,以便我可以参考对话的标题。我可以做些什么来在MessageConversation 中成功创建Foreignkey 字段,而无需更改模型的结构?提前感谢您的回答!

【问题讨论】:

标签: django django-models django-south django-migrations


【解决方案1】:

您应该使用字符串值来引用模型。但是,在我看来,这两个模型都应该包含在同一个应用程序中。只看这段代码就会让人觉得设计很糟糕,因为应用不应该有这样的循环引用。

root_message 也应该是 OneToOneField,因为一条消息与单个对话相关联,因此一条消息不可能成为多个对话的根。

class Conversation(models.Model):
    title = models.CharField('Conversation Title', max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)
    composer = models.ForeignKey(User)
    root_message =  models.ForeignKey('messages.Message', null=True, blank=True)

class Message(models.Model):
    conversation = models.ForeignKey('conversations.Conversation', null=True, blank=True)
    content = models.TextField(db_index=True, max_length=500)
    created_at = models.DateTimeField(auto_now_add=True)

【讨论】:

  • 谢谢。使用字符串值引用模型解决了循环引用问题。在Message 模型定义中,我声明:campaign = models.ForeignKey('campaigns.Campaign', null=True, blank=True)。再次感谢您的回答和建议。
  • 请考虑我的另外两个建议。
  • 是的。会做。我认为它会使模型配置更清晰。谢谢你。 :)
猜你喜欢
  • 1970-01-01
  • 2014-03-10
  • 2015-02-19
  • 2011-10-18
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
  • 2020-08-28
相关资源
最近更新 更多