Fixed #10929 -- Added default argument to aggregates.

Thanks to Simon Charette and Adam Johnson for the reviews.
This commit is contained in:
Nick Pope 2021-02-21 01:38:55 +00:00 committed by Mariusz Felisiak
parent 59942a66ce
commit 501a8db465
11 changed files with 393 additions and 64 deletions

View file

@ -19,8 +19,8 @@ module. They are described in more detail in the `PostgreSQL docs
.. admonition:: Common aggregate options
All aggregates have the :ref:`filter <aggregate-filter>` keyword
argument.
All aggregates have the :ref:`filter <aggregate-filter>` keyword argument
and most also have the :ref:`default <aggregate-default>` keyword argument.
General-purpose aggregation functions
=====================================
@ -28,9 +28,10 @@ General-purpose aggregation functions
``ArrayAgg``
------------
.. class:: ArrayAgg(expression, distinct=False, filter=None, ordering=(), **extra)
.. class:: ArrayAgg(expression, distinct=False, filter=None, default=None, ordering=(), **extra)
Returns a list of values, including nulls, concatenated into an array.
Returns a list of values, including nulls, concatenated into an array, or
``default`` if there are no values.
.. attribute:: distinct
@ -54,26 +55,26 @@ General-purpose aggregation functions
``BitAnd``
----------
.. class:: BitAnd(expression, filter=None, **extra)
.. class:: BitAnd(expression, filter=None, default=None, **extra)
Returns an ``int`` of the bitwise ``AND`` of all non-null input values, or
``None`` if all values are null.
``default`` if all values are null.
``BitOr``
---------
.. class:: BitOr(expression, filter=None, **extra)
.. class:: BitOr(expression, filter=None, default=None, **extra)
Returns an ``int`` of the bitwise ``OR`` of all non-null input values, or
``None`` if all values are null.
``default`` if all values are null.
``BoolAnd``
-----------
.. class:: BoolAnd(expression, filter=None, **extra)
.. class:: BoolAnd(expression, filter=None, default=None, **extra)
Returns ``True``, if all input values are true, ``None`` if all values are
null or if there are no values, otherwise ``False`` .
Returns ``True``, if all input values are true, ``default`` if all values
are null or if there are no values, otherwise ``False``.
Usage example::
@ -92,9 +93,9 @@ General-purpose aggregation functions
``BoolOr``
----------
.. class:: BoolOr(expression, filter=None, **extra)
.. class:: BoolOr(expression, filter=None, default=None, **extra)
Returns ``True`` if at least one input value is true, ``None`` if all
Returns ``True`` if at least one input value is true, ``default`` if all
values are null or if there are no values, otherwise ``False``.
Usage example::
@ -114,9 +115,10 @@ General-purpose aggregation functions
``JSONBAgg``
------------
.. class:: JSONBAgg(expressions, distinct=False, filter=None, ordering=(), **extra)
.. class:: JSONBAgg(expressions, distinct=False, filter=None, default=None, ordering=(), **extra)
Returns the input values as a ``JSON`` array.
Returns the input values as a ``JSON`` array, or ``default`` if there are
no values.
.. attribute:: distinct
@ -139,10 +141,10 @@ General-purpose aggregation functions
``StringAgg``
-------------
.. class:: StringAgg(expression, delimiter, distinct=False, filter=None, ordering=())
.. class:: StringAgg(expression, delimiter, distinct=False, filter=None, default=None, ordering=())
Returns the input values concatenated into a string, separated by
the ``delimiter`` string.
the ``delimiter`` string, or ``default`` if there are no values.
.. attribute:: delimiter
@ -174,17 +176,17 @@ field or an expression returning a numeric data. Both are required.
``Corr``
--------
.. class:: Corr(y, x, filter=None)
.. class:: Corr(y, x, filter=None, default=None)
Returns the correlation coefficient as a ``float``, or ``None`` if there
Returns the correlation coefficient as a ``float``, or ``default`` if there
aren't any matching rows.
``CovarPop``
------------
.. class:: CovarPop(y, x, sample=False, filter=None)
.. class:: CovarPop(y, x, sample=False, filter=None, default=None)
Returns the population covariance as a ``float``, or ``None`` if there
Returns the population covariance as a ``float``, or ``default`` if there
aren't any matching rows.
Has one optional argument:
@ -198,18 +200,18 @@ field or an expression returning a numeric data. Both are required.
``RegrAvgX``
------------
.. class:: RegrAvgX(y, x, filter=None)
.. class:: RegrAvgX(y, x, filter=None, default=None)
Returns the average of the independent variable (``sum(x)/N``) as a
``float``, or ``None`` if there aren't any matching rows.
``float``, or ``default`` if there aren't any matching rows.
``RegrAvgY``
------------
.. class:: RegrAvgY(y, x, filter=None)
.. class:: RegrAvgY(y, x, filter=None, default=None)
Returns the average of the dependent variable (``sum(y)/N``) as a
``float``, or ``None`` if there aren't any matching rows.
``float``, or ``default`` if there aren't any matching rows.
``RegrCount``
-------------
@ -219,56 +221,60 @@ field or an expression returning a numeric data. Both are required.
Returns an ``int`` of the number of input rows in which both expressions
are not null.
.. note::
The ``default`` argument is not supported.
``RegrIntercept``
-----------------
.. class:: RegrIntercept(y, x, filter=None)
.. class:: RegrIntercept(y, x, filter=None, default=None)
Returns the y-intercept of the least-squares-fit linear equation determined
by the ``(x, y)`` pairs as a ``float``, or ``None`` if there aren't any
by the ``(x, y)`` pairs as a ``float``, or ``default`` if there aren't any
matching rows.
``RegrR2``
----------
.. class:: RegrR2(y, x, filter=None)
.. class:: RegrR2(y, x, filter=None, default=None)
Returns the square of the correlation coefficient as a ``float``, or
``None`` if there aren't any matching rows.
``default`` if there aren't any matching rows.
``RegrSlope``
-------------
.. class:: RegrSlope(y, x, filter=None)
.. class:: RegrSlope(y, x, filter=None, default=None)
Returns the slope of the least-squares-fit linear equation determined
by the ``(x, y)`` pairs as a ``float``, or ``None`` if there aren't any
by the ``(x, y)`` pairs as a ``float``, or ``default`` if there aren't any
matching rows.
``RegrSXX``
-----------
.. class:: RegrSXX(y, x, filter=None)
.. class:: RegrSXX(y, x, filter=None, default=None)
Returns ``sum(x^2) - sum(x)^2/N`` ("sum of squares" of the independent
variable) as a ``float``, or ``None`` if there aren't any matching rows.
variable) as a ``float``, or ``default`` if there aren't any matching rows.
``RegrSXY``
-----------
.. class:: RegrSXY(y, x, filter=None)
.. class:: RegrSXY(y, x, filter=None, default=None)
Returns ``sum(x*y) - sum(x) * sum(y)/N`` ("sum of products" of independent
times dependent variable) as a ``float``, or ``None`` if there aren't any
matching rows.
times dependent variable) as a ``float``, or ``default`` if there aren't
any matching rows.
``RegrSYY``
-----------
.. class:: RegrSYY(y, x, filter=None)
.. class:: RegrSYY(y, x, filter=None, default=None)
Returns ``sum(y^2) - sum(y)^2/N`` ("sum of squares" of the dependent
variable) as a ``float``, or ``None`` if there aren't any matching rows.
variable) as a ``float``, or ``default`` if there aren't any matching rows.
Usage examples
==============

View file

@ -59,7 +59,7 @@ will result in a database error.
Usage examples::
>>> # Get a screen name from least to most public
>>> from django.db.models import Sum, Value as V
>>> from django.db.models import Sum
>>> from django.db.models.functions import Coalesce
>>> Author.objects.create(name='Margaret Smith', goes_by='Maggie')
>>> author = Author.objects.annotate(
@ -68,13 +68,18 @@ Usage examples::
Maggie
>>> # Prevent an aggregate Sum() from returning None
>>> # The aggregate default argument uses Coalesce() under the hood.
>>> aggregated = Author.objects.aggregate(
... combined_age=Coalesce(Sum('age'), V(0)),
... combined_age_default=Sum('age'))
... combined_age=Sum('age'),
... combined_age_default=Sum('age', default=0),
... combined_age_coalesce=Coalesce(Sum('age'), 0),
... )
>>> print(aggregated['combined_age'])
0
>>> print(aggregated['combined_age_default'])
None
>>> print(aggregated['combined_age_default'])
0
>>> print(aggregated['combined_age_coalesce'])
0
.. warning::

View file

@ -393,7 +393,7 @@ some complex computations::
The ``Aggregate`` API is as follows:
.. class:: Aggregate(*expressions, output_field=None, distinct=False, filter=None, **extra)
.. class:: Aggregate(*expressions, output_field=None, distinct=False, filter=None, default=None, **extra)
.. attribute:: template
@ -452,6 +452,11 @@ The ``filter`` argument takes a :class:`Q object <django.db.models.Q>` that's
used to filter the rows that are aggregated. See :ref:`conditional-aggregation`
and :ref:`filtering-on-annotations` for example usage.
The ``default`` argument takes a value that will be passed along with the
aggregate to :class:`~django.db.models.functions.Coalesce`. This is useful for
specifying a value to be returned other than ``None`` when the queryset (or
grouping) contains no entries.
The ``**extra`` kwargs are ``key=value`` pairs that can be interpolated
into the ``template`` attribute.
@ -459,6 +464,10 @@ into the ``template`` attribute.
Support for transforms of the field was added.
.. versionchanged:: 4.0
The ``default`` argument was added.
Creating your own Aggregate Functions
-------------------------------------

View file

@ -3540,8 +3540,10 @@ documentation to learn how to create your aggregates.
Aggregation functions return ``None`` when used with an empty
``QuerySet``. For example, the ``Sum`` aggregation function returns ``None``
instead of ``0`` if the ``QuerySet`` contains no entries. An exception is
``Count``, which does return ``0`` if the ``QuerySet`` is empty.
instead of ``0`` if the ``QuerySet`` contains no entries. To return another
value instead, pass a value to the ``default`` argument. An exception is
``Count``, which does return ``0`` if the ``QuerySet`` is empty. ``Count``
does not support the ``default`` argument.
All aggregates have the following parameters in common:
@ -3578,6 +3580,16 @@ rows that are aggregated.
See :ref:`conditional-aggregation` and :ref:`filtering-on-annotations` for
example usage.
.. _aggregate-default:
``default``
~~~~~~~~~~~
.. versionadded:: 4.0
An optional argument that allows specifying a value to use as a default value
when the queryset (or grouping) contains no entries.
``**extra``
~~~~~~~~~~~
@ -3587,7 +3599,7 @@ by the aggregate.
``Avg``
~~~~~~~
.. class:: Avg(expression, output_field=None, distinct=False, filter=None, **extra)
.. class:: Avg(expression, output_field=None, distinct=False, filter=None, default=None, **extra)
Returns the mean value of the given expression, which must be numeric
unless you specify a different ``output_field``.
@ -3623,10 +3635,14 @@ by the aggregate.
This is the SQL equivalent of ``COUNT(DISTINCT <field>)``. The default
value is ``False``.
.. note::
The ``default`` argument is not supported.
``Max``
~~~~~~~
.. class:: Max(expression, output_field=None, filter=None, **extra)
.. class:: Max(expression, output_field=None, filter=None, default=None, **extra)
Returns the maximum value of the given expression.
@ -3636,7 +3652,7 @@ by the aggregate.
``Min``
~~~~~~~
.. class:: Min(expression, output_field=None, filter=None, **extra)
.. class:: Min(expression, output_field=None, filter=None, default=None, **extra)
Returns the minimum value of the given expression.
@ -3646,7 +3662,7 @@ by the aggregate.
``StdDev``
~~~~~~~~~~
.. class:: StdDev(expression, output_field=None, sample=False, filter=None, **extra)
.. class:: StdDev(expression, output_field=None, sample=False, filter=None, default=None, **extra)
Returns the standard deviation of the data in the provided expression.
@ -3664,7 +3680,7 @@ by the aggregate.
``Sum``
~~~~~~~
.. class:: Sum(expression, output_field=None, distinct=False, filter=None, **extra)
.. class:: Sum(expression, output_field=None, distinct=False, filter=None, default=None, **extra)
Computes the sum of all values of the given expression.
@ -3682,7 +3698,7 @@ by the aggregate.
``Variance``
~~~~~~~~~~~~
.. class:: Variance(expression, output_field=None, sample=False, filter=None, **extra)
.. class:: Variance(expression, output_field=None, sample=False, filter=None, default=None, **extra)
Returns the variance of the data in the provided expression.

View file

@ -288,6 +288,10 @@ Models
* :class:`~django.db.models.Lookup` expressions may now be used in ``QuerySet``
annotations, aggregations, and directly in filters.
* The new :ref:`default <aggregate-default>` argument for built-in aggregates
allows specifying a value to be returned when the queryset (or grouping)
contains no entries, rather than ``None``.
Requests and Responses
~~~~~~~~~~~~~~~~~~~~~~