3

到目前为止,我有一个模型可以向用户发送消息。我可以检查发送给用户的所有消息或用户收到的消息。但是我如何获取特定用户的所有消息(发送/接收)?如果我的模型设计错误,请纠正我。谢谢你。

模型.py:

class Message(models.Model):
    description = models.TextField()
    date_added = models.DateTimeField(default=datetime.now)
    sender = models.ForeignKey(User, related_name='sent_set')
    recipient = models.ForeignKey(User, related_name='recieved_set')

    def __unicode__(self):
        return "%s sent message: %s to %s" % (self.sender, self.description, self.recipient)

    def save(self, **kwargs):
        if self.sender == self.recipient:
            raise ValueError("Cannot message yourself")
        super(Message, self).save(**kwargs)
4

1 回答 1

2
from django.db.models import Q
user = request.user #or something else
Message.objects.filter(Q(sender=user)|Q(recipient=user))

您应该阅读https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

于 2013-08-16T17:50:33.723 回答