Salarsf
Salarsf

Reputation: 1

How can I get unread messages for each user?

I'm creating a django web application. I want to create a one way messaging system so users can receive messages from admin. Currently I did this using a model like below:

from django.db import models
from django.contrib.auth.models import User

class AdminMessage(models.Model):
    title = models.CharField(max_length=120)
    receivers = models.ManyToManyField(User)
    message = models.TextField()
    is_read = models.BooleanField(default=False)

the problem is I want each user to be able to see his unread messages in his profile. how can I do that?

Upvotes: 0

Views: 178

Answers (1)

AKX
AKX

Reputation: 169042

If you want each receiver to also have an unread state for the message, you will need a model for that:

class AdminMessageReceiver(models.Model):
    message = models.ForeignKey(AdminMessage)
    receiver = models.ForeignKey(User)
    is_read = models.BooleanField(default=False)

You can then hook this up as a through model on the many-to-many relationship:

class AdminMessage(models.Model):
    title = models.CharField(max_length=120)
    receivers = models.ManyToManyField(User, through=AdminMessageReceiver)
    message = models.TextField()

Upvotes: 1

Related Questions