首页 > 解决方案 > 仅显示与同一用户 Django 关联的最后一条未读消息

问题描述

我有一个通知下拉列表,显示登录用户所属的任何线程中的未读消息。

例如,山姆和简。

Jane 与 3 个不同的人在 3 个线程中。山姆连续给她发了 6 条信息。现在,通知下拉列表显示来自 Sam 的所有 6 条未读消息,效率低下。

即使红色的未读通知会显示6下拉列表,也应该只显示来自 Sam 的最后一条未读消息。

我遇到了麻烦,因为我不知道要过滤什么才能仅提取/显示最后一条消息。该Notification模型只有 3 个字段。

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)

当用户发送消息时,它被保存为一个Notification对象,接收用户为notification_user.

所以现在我有这个功能

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()

它显示了与登录用户相关的所有read/unread通知,但这显然显示了来自 Sam 的所有 6 条消息。

模型.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)

consumer.py(创建通知的地方)

  @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

示例 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>

标签: djangodjango-modelsdjango-viewsdjango-template-filters

解决方案


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

不要忘记添加正确的,order_by否则“最后一条记录”会有点随机。


推荐阅读