【问题标题】:Annotate many to many with initial model django使用初始模型 django 注释多对多
【发布时间】:2018-01-25 20:24:03
【问题描述】:

我有这两个模型

class Word(Model):
    word = CharField()
    categories = ManyToManyField('Category')

class Category(Model):
    name = CharField()

我要做的是为每组类别输出单词数:

General (3 words)
General, IT (7 words)
Medicine (1 word)
Archaic Words, IT (10 words)

这意味着,例如,有 3 个单词,只有一个类别,即 General。

在尽可能少的查询中完成它的方法是什么?

第一步是获取所有可能的集合,我使用 PostgreSQL: all_sets = Word.objects.annotate(category_names=ArrayAgg('categories__name')).values_list('category_names', flat=True).distinct()

接下来呢? 当然,我可以获取每组的字数:

for category_set in all_sets:
    queryset = Word.objects.annotate(n=Count('categories')).filter(n=len(category_set))
    for cat in category_set:
        queryset = queryset.filter(categories__name=cat)

但我会为每组类别访问数据库。 这可以改进吗?

【问题讨论】:

    标签: django postgresql django-models


    【解决方案1】:

    使用以下内容在单个查询中获取所有内容:

    categories = Category.objects.annotate(n_words=Count('word_set'))
    for category in categories:
        print('{category.name} ({category.n_words})'.format(category))
    

    【讨论】:

      猜你喜欢
      • 2014-11-13
      • 2023-01-21
      • 2021-10-22
      • 2016-07-17
      • 1970-01-01
      • 2021-01-25
      • 2011-04-06
      • 1970-01-01
      • 2019-09-15
      相关资源
      最近更新 更多