Django通过项数查询多对多关系

时间:2018-08-12 10:25:28

标签: python django python-3.x

我有word模型和phrase模型

class Word(models.Model): 
        ....

class Phrase(models.Model):
    words = models.ManyToManyField(Word, null=True,related_name = "phrases")

我需要执行一个复杂的查询:

  • 我们说Wordunique,如果它仅属于一个 Phrase
  • 如果Phrase具有至少 2个唯一词=>我们说它是special
  • 我需要找到所有可以在特殊短语中找到的词

到目前为止,我正在通过使用for..in循环进行迭代,但这似乎并不有效。 我该怎么做呢? (短语将始终至少包含一个单词,而单词将始终包含至少一个短语。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那可能会起作用:)

from django.db.models import Count

special_phrases = Phrase.objects.annotate(
    count=Count('words')).filter(
    count__gte=2).values_list('id', flat=True)

result = Word.objects.filter(phrases__id__in=special_phrases)