Django-在 ManyToMany 字段上进行精确匹配的过滤

问题描述 投票:0回答:2

我有以下型号:

class Hashtag(models.Model):
    title = models.CharField(...)


class Annotation(models.Model):
    ...
    hashtags = models.ManyToManyField(Hashtag)

我想要获得所有

[hashtag_1, hashtag_2, hashtag_3]
作为主题标签的注释。

以下是我的询问:

annotations = Annotation.objects.filter(
    hashtags__title__in=["hashtag_1", "hashtag_2", "hashtag_3"]
)

此查询集返回至少具有

["hashtag_1", "hashtag_2", "hashtag_3"]
之一的所有注释,但我想接收具有 only 这 3 个主题标签(不大于也不小于这些主题标签)的注释。
我怎样才能做到这一点?
我还尝试了以下查询:

annotations = Annotation.objects.annotate(
    hashtag_count=Count("hashtags")
).filter(
    hashtags__title__in=["hashtag_1", "hashtag_2", "hashtag_3"],
    hashtag_count=3
)

如果注释有

[hashtag_1, hashtag_2, hashtag_n]
,此查询将返回它(这不是我想要的)

django django-queryset django-orm django-filter
2个回答
0
投票

试试这个:

Annotation.objects.filter(
    hashtags__title="hashtag_1"
).filter(
    hashtags__title="hashtag_2"
).filter(
    hashtags__title="hashtag_3"
)

0
投票

from django.db.models import Q

target_hashtags = ["hashtag_1", "hashtag_2", "hashtag_3"]

为第一个主题标签初始化 Q 对象。

query = Q(hashtags__title=target_hashtags[0])

使用逻辑 AND 使用循环构建剩余主题标签的查询。

for hashtag in target_hashtags[1:]:

query &= Q(hashtags__title=hashtag)

获取包含所有三个主题标签的注释。

annotations_with_all_hashtags = Annotation.objects.filter(query)

现在,annotations_with_all_hashtags 包含具有所有三个指定主题标签的注释。

© www.soinside.com 2019 - 2024. All rights reserved.