Reputation: 1779
Till now I have an model to send messages to users. I can check all the messages sent to a user or messages recieved by the user. But how do i get all the messages (sent/recieved) of a particular user? And please correct me, if my model design is wrong. Thank you.
model.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)
Upvotes: 3
Views: 245
Reputation: 15241
from django.db.models import Q
user = request.user #or something else
Message.objects.filter(Q(sender=user)|Q(recipient=user))
You should read https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects
Upvotes: 2