我有以下型号:
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]
,此查询将返回它(这不是我想要的)
试试这个:
Annotation.objects.filter(
hashtags__title="hashtag_1"
).filter(
hashtags__title="hashtag_2"
).filter(
hashtags__title="hashtag_3"
)
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 包含具有所有三个指定主题标签的注释。