Как отфильтровать набор запросов по полю many2many

У меня есть модель Notification, в которой есть поле seen_users, названное так:

from django.contrib.auth import get_user_model

User = get_user_model()

class Notification(models.Model):
    title = models.CharField(max_length=255)
    seen_users = models.ManyToManyField(User, blank=True)

Когда пользователь видит уведомление (например, notification_obj), он будет добавлен в notification_obj.seen_users.

Теперь как я могу отфильтровать уведомления, которые не видел определенный пользователь, например user1 Наиболее эффективным способом ?

Я пытался сделать запрос, как показано ниже:

class NotificationView(generics.ListAPIView):
    authentication_classess = [TokenAuthentication]
    permission_classes = []

    def get_queryset(self):
        unseen_only = self.request.GET.get("unseen_only", "0")
        if unseen_only == "1":
            
            # THIS IS WHERE I GOT TROUBLES
            # Because other users may have seen this and its not empty
            return Notification.objects.filter(seen_users__in=[]) 

        return Notification.objects.all()

Используйте .exclude(…) [Django-doc]:

Notification.objects.exclude(seen_users=request.user)

Таким образом, из набора запросов будут исключены те Notification, в которых request.user является членом.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Вернуться на верх