Search code examples
djangodjango-modelsdjango-viewsdjango-template-filters

Display only last unread message associated with same user Django


I have a notification dropdown that displays unread messages in any threads that the logged in user is a part of.

Example, Sam and Jane.

Jane is in 3 threads with 3 different people. Sam has sent her 6 messages in a row. Right now, the notification dropdown displays all 6 unread messages from Sam, which is inefficient.

Even though the red unread notification will show 6 the dropdown should display only the last unread message from Sam.

I'm having trouble with this because I don't know what to filter by in order to extract/display only the last message. The Notification model only has 3 fields.

class Notification(models.Model):
    notification_user = models.ForeignKey(User, on_delete=models.CASCADE)
    notification_chat = models.ForeignKey(ChatMessage, on_delete=models.CASCADE)
    notification_read = models.BooleanField(default=False)

When a user sends a message, it is saved as a Notification object with the receiving user as notification_user.

So right now I have this function

def notification(request):
    if request.user.is_authenticated:
        notification = Notification.objects.filter(notification_user=request.user, notification_read=False)
        notification_read = Notification.objects.filter(notification_user=request.user, notification_read=True)
        return {
            'notification':notification,
            'notification_read':notification_read
        }
    return Notification.objects.none()

Which displays all read/unread notifications associated with the logged in user, but that obviously shows all 6 messages from Sam.

models.py

class Thread(models.Model):
    first        = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first')
    second       = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second')
    updated      = models.DateTimeField(auto_now=True)
    timestamp    = models.DateTimeField(auto_now_add=True)

    objects      = ThreadManager()

class ChatMessage(models.Model):
    thread      = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.SET_NULL)
    user        = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='sender', on_delete=models.CASCADE)
    message     = models.TextField()
    timestamp   = models.DateTimeField(auto_now_add=True)

consumers.py (where notification is created)

  @database_sync_to_async
    def get_thread(self, user, other_username):
        return Thread.objects.get_or_new(user, other_username)[0]

    @database_sync_to_async
    def create_chat_message(self, me, msg):
        thread_obj = self.thread_obj
        return ChatMessage.objects.create(thread=thread_obj, user=me, message=msg)

    @database_sync_to_async
    def create_notification(self, other_user, msg):
        last_chat = ChatMessage.objects.latest('id')
        created_notification = Notification.objects.create(notification_user=other_user, notification_chat=last_chat)
        return created_notification

example navbar.html

{% for notifications in notification_read|slice:"0:6" %}
                  <li><a href="{% url 'thread' user %}">
                    <span id="notification-{{notification.id}}">
                      '{{ notifications.notification_chat.message }}'
                      -{{ notifications.notification_chat.user }}
                    </span>
                  </a></li>

Solution

  • Notification.objects.filter(
        notification_user=request.user, notification_read=True
    ).order_by('-notification_chat__timestamp')[:1]
    

    Don't forget to add correct order_by otherwise "last record" will be a bit random.