Specify ordering for querysets using annotate() to count related objects #3872

Closed
opened 2025-12-29 18:31:43 +01:00 by adam · 0 comments
Owner

Originally created by @jeremystretch on GitHub (Jul 20, 2020).

Originally assigned to: @jeremystretch on GitHub.

Proposed Changes

Append order_by() to every queryset which annotates a count of one or more related objects. For example:

Provider.objects.annotate(count_circuits=Count('circuits'))

becomes

Provider.objects.annotate(count_circuits=Count('circuits')).order_by(*Provider._meta.ordering)

Note: This change is not needed for MPTT models, as they are ordered according to the tree.

Justification

Django 3.1 ignores a model's default ordering when a GROUP BY clause is present in the query. Because we can't currently switch to using subqueries everywhere without breaking caching (see Suor/django-cacheops#365), we need to specify ordering manually to preserve the current behavior.

This can be reversed in the future under #4865.

Originally created by @jeremystretch on GitHub (Jul 20, 2020). Originally assigned to: @jeremystretch on GitHub. ### Proposed Changes Append `order_by()` to every queryset which annotates a count of one or more related objects. For example: ```python Provider.objects.annotate(count_circuits=Count('circuits')) ``` becomes ```python Provider.objects.annotate(count_circuits=Count('circuits')).order_by(*Provider._meta.ordering) ``` **Note:** This change is _not_ needed for MPTT models, as they are ordered according to the tree. ### Justification Django 3.1 [ignores a model's default ordering](https://docs.djangoproject.com/en/3.0/topics/db/aggregation/#aggregation-ordering-interaction) when a `GROUP BY` clause is present in the query. Because we can't currently switch to using subqueries everywhere without breaking caching (see Suor/django-cacheops#365), we need to specify ordering manually to preserve the current behavior. This can be reversed in the future under #4865.
adam added the status: acceptedtype: housekeeping labels 2025-12-29 18:31:43 +01:00
adam closed this issue 2025-12-29 18:31:43 +01:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/netbox#3872