PostgreSQL 特有聚合函数Link to this heading

这些功能可以从 django.contrib.postgres.aggregates 模块中获得。在 PostgreSQL docs 中对这些功能有更详细的描述。

通用聚合函数Link to this heading

ArrayAggLink to this heading

class ArrayAgg(expression, distinct=False, filter=None, default=None, order_by=(), **extra)Link to this definition

返回一个值的列表,包括空值,串联成一个数组,如果没有值,则返回 default

distinctLink to this definition

一个可选的布尔参数,用于确定数组值是否会被去重。默认值为 False

order_byLink to this definition

可选的字段名字符串(可选的 "-" 前缀表示降序)或表达式(或字符串和/或表达式的元组或列表),指定结果列表中元素的顺序。

举例:

Code
from django.db.models import F

ArrayAgg("a_field", order_by="-some_field")
ArrayAgg("a_field", order_by=F("some_field").desc())

BitAndLink to this heading

class BitAnd(expression, filter=None, default=None, **extra)Link to this definition

返回所有非空输入值的位式 ANDint,如果所有值为空,则返回 default

BitOrLink to this heading

class BitOr(expression, filter=None, default=None, **extra)Link to this definition

返回所有非空输入值的位式 ORint,如果所有值为空,则返回 default

BitXorLink to this heading

class BitXor(expression, filter=None, default=None, **extra)Link to this definition

返回所有非空输入值的按位异或(XOR)的整数,如果所有值都为空,则返回 default。需要 PostgreSQL 14+。

BoolAndLink to this heading

class BoolAnd(expression, filter=None, default=None, **extra)Link to this definition

如果所有输入值为真,返回 True,如果所有值为空或没有值,返回 default,否则返回 False

使用实例:

Code
class Comment(models.Model):
    body = models.TextField()
    published = models.BooleanField()
    rank = models.IntegerField()
Python console
>>> from django.db.models import Q
>>> from django.contrib.postgres.aggregates import BoolAnd
>>> Comment.objects.aggregate(booland=BoolAnd("published"))
{'booland': False}
>>> Comment.objects.aggregate(booland=BoolAnd(Q(rank__lt=100)))
{'booland': True}

BoolOrLink to this heading

class BoolOr(expression, filter=None, default=None, **extra)Link to this definition

如果至少有一个输入值为真,则返回 True,如果所有值都为空或没有值,则返回 default,否则返回 False

使用实例:

Code
class Comment(models.Model):
    body = models.TextField()
    published = models.BooleanField()
    rank = models.IntegerField()
Python console
>>> from django.db.models import Q
>>> from django.contrib.postgres.aggregates import BoolOr
>>> Comment.objects.aggregate(boolor=BoolOr("published"))
{'boolor': True}
>>> Comment.objects.aggregate(boolor=BoolOr(Q(rank__gt=2)))
{'boolor': False}

JSONBAggLink to this heading

class JSONBAgg(expressions, distinct=False, filter=None, default=None, order_by=(), **extra)Link to this definition

返回输入值为 JSON 数组,如果没有值,则返回 default。你可以使用 key index 查找 来查询结果。

distinctLink to this definition

一个可选的布尔参数,用于确定数组值是否会被去重。默认值为 False

order_byLink to this definition

可选的字段名字符串(可选的 "-" 前缀表示降序)或表达式(或字符串和/或表达式的元组或列表),指定结果列表中元素的顺序。

Examples are the same as for ArrayAgg.order_by.

使用实例:

Code
class Room(models.Model):
    number = models.IntegerField(unique=True)


class HotelReservation(models.Model):
    room = models.ForeignKey("Room", on_delete=models.CASCADE)
    start = models.DateTimeField()
    end = models.DateTimeField()
    requirements = models.JSONField(blank=True, null=True)
Python console
>>> from django.contrib.postgres.aggregates import JSONBAgg
>>> Room.objects.annotate(
...     requirements=JSONBAgg(
...         "hotelreservation__requirements",
...         order_by="-hotelreservation__start",
...     )
... ).filter(requirements__0__sea_view=True).values("number", "requirements")
<QuerySet [{'number': 102, 'requirements': [
    {'parking': False, 'sea_view': True, 'double_bed': False},
    {'parking': True, 'double_bed': True}
]}]>

StringAggLink to this heading

class StringAgg(expression, delimiter, distinct=False, filter=None, default=None, order_by=())Link to this definition

返回输入值串联成的字符串,用 delimiter 字符串分隔,如果没有值,则返回 default

delimiterLink to this definition

Required argument. A string, Value, or expression representing the string for separating values. For example, Value(",").

distinctLink to this definition

一个可选的布尔参数,用于确定连接的值是否是不同的。默认值为 False

order_byLink to this definition

可选的字段名字符串(可选的 "-" 前缀表示降序)或表达式(或字符串和/或表达式的元组或列表),指定结果字符串中元素的顺序。

Examples are the same as for ArrayAgg.order_by.

使用实例:

Code
class Publication(models.Model):
    title = models.CharField(max_length=30)


class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)
Python console
>>> article = Article.objects.create(headline="NASA uses Python")
>>> article.publications.create(title="The Python Journal")
<Publication: Publication object (1)>
>>> article.publications.create(title="Science News")
<Publication: Publication object (2)>
>>> from django.contrib.postgres.aggregates import StringAgg
>>> Article.objects.annotate(
...     publication_names=StringAgg(
...         "publications__title",
...         delimiter=", ",
...         order_by="publications__title",
...     )
... ).values("headline", "publication_names")
<QuerySet [{
    'headline': 'NASA uses Python', 'publication_names': 'Science News, The Python Journal'
}]>

统计的聚合功能Link to this heading

yxLink to this heading

所有这些函数的参数 yx 可以是字段名或返回数值数据的表达式。这两个参数都是必须的。

CorrLink to this heading

class Corr(y, x, filter=None, default=None)Link to this definition

返回相关系数为 float,如果没有任何匹配行,则返回 default

CovarPopLink to this heading

class CovarPop(y, x, sample=False, filter=None, default=None)Link to this definition

返回人口协方差为 float,如果没有任何匹配的行,则返回 default

sampleLink to this definition

可选。默认情况下,CovarPop 返回总体协方差。但是,如果 sample=True,返回值将是样本协方差。

RegrAvgXLink to this heading

class RegrAvgX(y, x, filter=None, default=None)Link to this definition

返回自变量的平均数(sum(x)/N)为 float,如果没有任何匹配的行,则返回 default

RegrAvgYLink to this heading

class RegrAvgY(y, x, filter=None, default=None)Link to this definition

返回因变量的平均数(sum(y)/N)为 float,如果没有匹配的行,则为 default

RegrCountLink to this heading

class RegrCount(y, x, filter=None)Link to this definition

返回两个表达式都不为空的输入行数的 int

RegrInterceptLink to this heading

class RegrIntercept(y, x, filter=None, default=None)Link to this definition

返回由 (x, y) 对确定的最小二乘法线性方程的 y 截距为 float,如果没有任何匹配行,则返回 default

RegrR2Link to this heading

class RegrR2(y, x, filter=None, default=None)Link to this definition

返回相关系数的平方为 float,如果没有任何匹配行,则返回 default

RegrSlopeLink to this heading

class RegrSlope(y, x, filter=None, default=None)Link to this definition

返回由 (x, y) 对确定的最小二乘法线性方程的斜率为 float,如果没有任何匹配行,则返回 default

RegrSXXLink to this heading

class RegrSXX(y, x, filter=None, default=None)Link to this definition

返回 sum(x^2) - sum(x)^2/N``(自变量的 “平方之和”)为 ``float,如果没有任何匹配的行,则返回 default

RegrSXYLink to this heading

class RegrSXY(y, x, filter=None, default=None)Link to this definition

返回 sum(x*y) - sum(x) * sum(y)/N``(自变量与因变量的“乘积之和”)为 ``float,如果没有任何匹配的行,则返回 default

RegrSYYLink to this heading

class RegrSYY(y, x, filter=None, default=None)Link to this definition

返回 sum(y^2) - sum(y)^2/N``(因变量的“平方之和”)为 ``float,如果没有任何匹配行,则返回 default

使用实例:Link to this heading

我们将使用这个示例表格:

Text
| FIELD1 | FIELD2 | FIELD3 |
|--------|--------|--------|
|    foo |      1 |     13 |
|    bar |      2 | (null) |
|   test |      3 |     13 |

以下是一些通用聚合函数的示例:

Python console
>>> TestModel.objects.aggregate(result=StringAgg("field1", delimiter=";"))
{'result': 'foo;bar;test'}
>>> TestModel.objects.aggregate(result=ArrayAgg("field2"))
{'result': [1, 2, 3]}
>>> TestModel.objects.aggregate(result=ArrayAgg("field1"))
{'result': ['foo', 'bar', 'test']}

下面的示例演示了统计聚合函数的用法。底层的数学原理将不会被描述(您可以在 维基百科 上了解更多信息):

Python console
>>> TestModel.objects.aggregate(count=RegrCount(y="field3", x="field2"))
{'count': 2}
>>> TestModel.objects.aggregate(
...     avgx=RegrAvgX(y="field3", x="field2"), avgy=RegrAvgY(y="field3", x="field2")
... )
{'avgx': 2, 'avgy': 13}