【发布时间】:2018-06-19 18:58:28
【问题描述】:
这是问题Django ManytoMany filter exact list的扩展
当列表包含重复项时,接受的答案似乎不起作用。 有什么解决办法吗?
基本上,我将句子拆分为标记,并希望通过这些标记进行搜索。
class Sentence(Model):
name = CharField()
class Tokens(Model):
token = CharField()
sentence = ForeignKey(Sentence, related_name='tokens')
假设,我有令牌['che', 'farebbe', 'dalle', 'dalle']。我想找到完全由这些标记组成的句子。
Sentence.objects.annotate(n=Count('tokens')).filter(tokens__name='che').filter(tokens__name='farebbe').filter(tokens__name='dalle').filter(n=4)
不起作用。 n 比 4 多(我猜是因为连接)。
如果令牌列表没有重复项,则一切正常。
【问题讨论】:
-
尝试使用
tokens__name__in链接过滤器似乎是多余的。 -
如果没有链接,它将给出空查询集。
-
所以这行不通
Sentence.objects.annotate(n=Count('tokens', distinct=True)).filter(tokens__name__in=['che', 'farebbe', 'dalle'], n=4) -
这可行,但不如预期。这将给出至少出现一个标记的句子。
-
试试
.filter(Q(tokens__name='che') & Q(tokens__name='farebbe') )
标签: python django django-models