Django: simple model for storing messages/notifications to/from users
<p>I am trying to create a simple Notification/Message model for my Django app. This will store notifications from the site to the user, and messages from one user to another. A working model I had been using looks like this:</p>

<pre><code>class Notification(models.Model):
    sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='sender_notification')
    recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='recipient_notification')
    message = models.TextField()
    read = models.BooleanField(default=False)
    recieved_date = models.DateTimeField(auto_now_add=True)
</code></pre>

<p>A message will have 0-1 senders (0 if the message is a notification from the site to the user), and typically one recipient (when the notification is meant for one specific user - e.g., "there is a comment on your post" - or when a message has been sent from one user to another). This had been working for me. However, it occurred to me that in some cases I want to send a notification to <em>every</em> user. I could potentially create <code>Notification</code> objects in a loop:</p>

<pre><code>for user in User.objects.all():
    Notification.objects.create(recipient=user, message='message for all uses')
</code></pre>

<p>But this seems like it will be pretty inefficient, and create unnecessary clutter in the database.</p>

<p>I experimented with updating my model like this:</p>

<pre><code>class Notification(models.Model):
    sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='sender_notification')
    recipient = models.ManyToManyField(User)
    message = models.TextField()
    read = models.BooleanField(default=False)
    recieved_date = models.DateTimeField(auto_now_add=True)
</code></pre>

<p>But this requires a <code>sender</code> (for reasons that I don't understand), and since there is only one record for each notification, when one recipient reads the notification and I set <code>read = True</code>, it will show as read for all recipients.</p>

<p><strong>Is there an easy solution that I am missing where I can use a single model to handle notifications/messages, or am I going to have to add some additional models (or duplicate notifications in the notifications table)?</strong> </p>

<p>Forgive my ignorance of database design. It is definitely a weakness of mine that I am working on.</p>

<p>My solution is to create a ReadFlag model.</p>

<pre><code>class ReadFlag(models.Model):
   user = models.ForeignKey(User)
   message = models.ForeignKey(Message)
   created = ...
</code></pre>

python django django-models