我有一个通知模型,其中有一个名为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
等特定用户未看到的通知?
我try 过像下面这样查询:
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()