python - 注释: whether a given value exists in m2m field

标签 python django django-rest-framework django-queryset drf-queryset

我有一个检索像这样的对象的查询:

{
    "id": 1,
    "tags": [1, 2, 3]
}

我想检查对象的 tags 字段中是否存在给定标签(例如 1),并将检查结果注释为以下字段:对象:

{
    "id": 1,
    "tagged": true
}

这就是我的想法

annotate(
    tagged=Exists(
        Articles.tag_set.through.objects.filter(
            article_id=OuterRef("pk"), tag_id=tag.id
        )
    )
)

由于关系 tags 已由主查询加载,因此辅助查询对我来说似乎是多余的。

是否有更简单的方法来构造此查询?类似于查找语法中的过滤器

最佳答案

假设标签是一个ArrayField

    q = Article.objects.annotate(
        tagged=Exists(
            Article.objects.filter(id=OuterRef('id'), tags__contains=[1])
        )
    )

关于python - 注释: whether a given value exists in m2m field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59164014/

相关文章:

Python/PyQt4 : How to make a QComboBox Item draggable

django - 将 Nginx 设置为 Apache 的反向代理与 Apache Event MPM 的反向代理

python - 创建时向 django-rest-framework ModelViewSet 添加其他字段的最佳方法

python - 如何在 Django REST API 框架中公开过滤的反向关系?

python - 如何验证 DRF 中的更新字段?

python 3.1 bool 检查与 for 循环

python - (matplotlib.pyplot) 散点图轴中的错误顺序

python - 如何解析 (1045, "Access denied for user ' User' @'IP or host' (using password : YES)") when build django docker container?

python - 如何从Python获取地址坐标

python - 在django中将注册表单填写到数据库后如何存储用户选择的单选按钮值?