【问题标题】:Django ManytoMany filter exact list with duplicate itemsDjango ManytoMany 过滤带有重复项的精确列表
【发布时间】: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)

不起作用。 n4 多(我猜是因为连接)。

如果令牌列表没有重复项,则一切正常。

【问题讨论】:

  • 尝试使用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


【解决方案1】:

找到解决方案:将distinct=True添加到Count

Sentence.objects.annotate(n=Count('tokens', distinct=True)).filter(tokens__name='che').filter(tokens__name='farebbe').filter(tokens__name='dalle').filter(n=4)

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 2018-05-13
    • 1970-01-01
    • 2018-01-21
    • 2016-06-16
    • 2020-10-17
    • 1970-01-01
    • 2016-04-11
    • 2012-12-12
    相关资源
    最近更新 更多