我有一个检索像这样的对象的查询:
{
"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/