为什么不能在django模型中为同一模型使用2个单独的外键

时间:2015-04-22 01:06:48

标签: python django foreign-keys chat

我有一个不起作用的理论模型:

class Message(models.Model):
       text = models.TextField()
       created = models.DateTimeField(auto_now_add=True)
       sender = models.ForeignKey(User)
       receiver = models.ForeignKey(User)

现在,如果用户向某人发送消息,例如私人消息线程,则会有人发送该消息,并且有人收到该消息,这一点很重要。我认为这两者都应该是一对多的,因为每个用户都可以发送无限的消息。发件人和收件人都是用户,来自同一型号的用户,但他们必须是不同的人。我得到django抱怨

django.core.management.base.CommandError: System check identified some issues:

ERRORS:
chat.Message.receiver: (fields.E304) Reverse accessor for 'Message.receiver' clashes with reverse accessor for 'Message.sender'.
    HINT: Add or change a related_name argument to the definition for 'Message.receiver' or 'Message.sender'.
chat.Message.sender: (fields.E304) Reverse accessor for 'Message.sender' clashes with reverse accessor for 'Message.receiver'.
    HINT: Add or change a related_name argument to the definition for 'Message.sender' or 'Message.receiver'.

我应该添加unique=True,因为您无法向自己发送消息吗?这是在用户之间实现消息的不好方法吗?我的错误是什么?谢谢,

科迪

1 个答案:

答案 0 :(得分:4)

正如错误消息所示,将related_name参数添加到外键定义:

class Message(models.Model):
    text        = models.TextField()
    created     = models.DateTimeField(auto_now_add=True)
    sender      = models.ForeignKey(User, related_name='messages_sent')
    receiver    = models.ForeignKey(User, related_name='messages_received')

这些相关名称可以在backward relations中使用,如下所示:

user = User.objects.get(username='johndoe')
messages_from = user.messages_sent.all()
messages_to = user.messages_received.all()

相当于:

user = User.objects.get(username='johndoe')
messages_from = Messages.objects.filter(sender=user)
messages_to = Messages.objects.filter(receiver=user)