我有一个通知模型,其中有一个名为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()

推荐答案

使用.exclude(…) [Django-doc]:

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

因此,这将从request.user是成员的查询集中排除Notification.


Note:通常使用settings.AUTH_USER_MODEL [Django-doc]来指代用户模型比直接使用User model [Django-doc]更好.有关更多信息,您可以查看referencing the User model section of the documentation.

Python相关问答推荐

修剪Python框架中的尾随NaN值

将大小为n*512的数组绘制到另一个大小为n*256的数组的PC组件

流畅的模式,采用Escc方法

使用Python从HTTP打印值

使用Python Great Expectations和python-oracledb

使用imap-tools时错误,其邮箱地址包含域名中的非默认字符

用Python获取HTML Span类中的数据

根据不同列的值在收件箱中移动数据

如何根据参数推断对象的返回类型?

在Google Colab中设置Llama-2出现问题-加载判断点碎片时Cell-run失败

如何访问所有文件,例如环境变量

如何在类和classy-fastapi -fastapi- followup中使用FastAPI创建路由

计算组中唯一值的数量

Python键入协议默认值

如何获得每个组的时间戳差异?

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

Scrapy和Great Expectations(great_expectations)—不合作

如何合并两个列表,并获得每个索引值最高的列表名称?

使用Python从rotowire中抓取MLB每日阵容

Python Pandas—时间序列—时间戳缺失时间精确在00:00