如何在 Django 中进行 GROUP BY 而不使用聚合函数?

ada*_*ith 10 django django-models

如何在 Django 中执行 GROUP BY 而不调用 Max、Sum、Avg 等聚合函数?

就我而言,我有一个表,其中包含诸如 , 之类的列{ local_path, parent, grandparent },并且我想要这样做SELECT local_path FROM ... WHERE grandparent = "foo" GROUP BY parent。将有多行的祖父母为“foo”且具有相同的父母,但我只想要其中一个(任何一个)local_path。

正如你所看到的,我不想获取任何东西的总价值。我无法让 unique() 工作,因为我想找到非不同的 local_paths。

我搜索并阅读了文档,但没有任何运气。谢谢!

Ste*_*sen 7

这里有一个技巧,可以让 DjangoGROUP BY在不运行聚合函数的情况下执行查询。我们创建了一个自定义Func子类,Django 将其视为聚合函数,但实际上只是NULL在 SQL 查询中计算结果。

from django.db.models import Func, CharField


class NullAgg(Func):
    """Annotation that causes GROUP BY without aggregating.

    A fake aggregate Func class that can be used in an annotation to cause
    a query to perform a GROUP BY without also performing an aggregate
    operation that would require the server to enumerate all rows in every
    group.

    Takes no constructor arguments and produces a value of NULL.

    Example:
        ContentType.objects.values('app_label').annotate(na=NullAgg())
    """
    template = 'NULL'
    contains_aggregate = True
    window_compatible = False
    arity = 0
    output_field = CharField()
Run Code Online (Sandbox Code Playgroud)


Ted*_*Ted 1

您可以使用 order_by('parent'),然后在模板中使用 {% ifchanged %} 仅显示其中之一。 https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#ifchanged