1👍
check the function extra
, it has a parameter called order_by
so you can use this function to order given QuerySet
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.extra
I guess it might be something like this:
labels = AssetLabel.objects. \
filter(organization=request.organization). \
extra(
select={'num_assets': "Count('asset')"},
order_by=['num_assets']
)
0👍
You should use annotate
before values
, the example from doc:
You should also note that average_rating has been explicitly included in the list of values to be returned. This is required because of the ordering of the values() and annotate() clause.
ValuesQuerySet will always contain the annotate field, iter it to remove the field,
values = labels.order_by('-num_assets')[:20].values('id', 'name')
for value in values:
value.pop('num_assets')
Source:stackexchange.com