diff options
| author | Tomer Chachamu <tomer.chachamu@gmail.com> | 2017-06-20 19:02:43 +0100 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2017-07-18 13:11:26 -0400 |
| commit | a5e91ab1fbf6badab51e04dd445d234bc11ddd0a (patch) | |
| tree | 552e9032144195416a969a7f4f36311960df5277 /docs/ref | |
| parent | 308945957cf0ae50f4ea33e42ab63a709afcc81c (diff) | |
[1.11.x] Doc'd the need to remove default ordering on Subquery aggregates.
Backport of 62917cee5ac75693aa5d9a3de5d8935da2f011df from master
Diffstat (limited to 'docs/ref')
| -rw-r--r-- | docs/ref/models/expressions.txt | 11 |
1 files changed, 6 insertions, 5 deletions
diff --git a/docs/ref/models/expressions.txt b/docs/ref/models/expressions.txt index 731a280939..dd38902479 100644 --- a/docs/ref/models/expressions.txt +++ b/docs/ref/models/expressions.txt @@ -608,15 +608,16 @@ Assuming both models have a ``length`` field, to find posts where the post length is greater than the total length of all combined comments:: >>> from django.db.models import OuterRef, Subquery, Sum - >>> comments = Comment.objects.filter(post=OuterRef('pk')).values('post') + >>> comments = Comment.objects.filter(post=OuterRef('pk')).order_by().values('post') >>> total_comments = comments.annotate(total=Sum('length')).values('total') >>> Post.objects.filter(length__gt=Subquery(total_comments)) The initial ``filter(...)`` limits the subquery to the relevant parameters. -``values('post')`` aggregates comments by ``Post``. Finally, ``annotate(...)`` -performs the aggregation. The order in which these queryset methods are applied -is important. In this case, since the subquery must be limited to a single -column, ``values('total')`` is required. +``order_by()`` removes the default :attr:`~django.db.models.Options.ordering` +(if any) on the ``Comment`` model. ``values('post')`` aggregates comments by +``Post``. Finally, ``annotate(...)`` performs the aggregation. The order in +which these queryset methods are applied is important. In this case, since the +subquery must be limited to a single column, ``values('total')`` is required. This is the only way to perform an aggregation within a ``Subquery``, as using :meth:`~.QuerySet.aggregate` attempts to evaluate the queryset (and if |
