'Filtering unseen messages in Python Django
I have two models, ChatBox and Message. I want to loop through all chats and display them, and I want to display a count of unseen messages (Message model is in a foreign key relation) for each chat.
Could anyone please help me to do this since I ve been strugling with it for few hours.
Firstly I wanted to pass each object from the loop to django filters/tags and add a count of unseen messages to it, but I got advised to use objects.annotation. However, i can not find ways to implement none of these.
Here is my view that displays inbox:
class InboxView(LoginRequiredMixin, ListView):
model = ChatBox
template_name = 'chat/inbox.html'
def get_queryset(self):
# getting all chats for a request.user
object_list = ChatBox.objects.filter(Q(user1=self.request.user) \
| Q(user2=self.request.user)).all()
return object_list
And here are my models:
class ChatBox(models.Model):
user1 = models.ForeignKey(CustomUser,
on_delete=models.CASCADE, related_name='user1')
user2 = models.ForeignKey(CustomUser,
on_delete=models.CASCADE, related_name='user2')
slug = models.SlugField(_("Slug"), max_length=255, unique=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Message(models.Model):
chat = models.ForeignKey(ChatBox, on_delete=models.CASCADE)
sender = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='sender')
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
seen = models.BooleanField(default=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
