Django ORM: Ordering w/ aggregate functions — None special treatment
Posted
by deno
on Stack Overflow
See other posts from Stack Overflow
or by deno
Published on 2010-04-03T18:20:28Z
Indexed on
2010/04/03
18:23 UTC
Read the original article
Hit count: 804
Hi,
I'm doing query like that:
SomeObject.objects.annotate(something=Avg('something')).order_by(something).all()
Now, I normally have an aggregate field in my model that I use with Django signals to keep in sync, however in this case perfomance isn't an issue so I thought I'd keep it simple and just use subqueries.
This approach, however, presented an unexpected issue: It all works grate if aggregate function results are like this:
[5.0, 4.0, 6.0 … (etc, just numbers)]
However if you mix in some Nones than it's being ordered like this:
[None, 5.0, 4.0 …]
The issue is that None has higher value than any number, while it should have value at most of 0.
I'm using PostgreSQL and haven't tested w/ other DBs. I haven't actually checked what query is generated etc.
I worked it around by just sorting in memory:
sorted(…, key=lambda _:_.avg_rating if _.avg_rating is not None else 0)
So I'm just curious if you know a way to do it w/ just Django ORM. Perhaps .where? or something…
Kind regards
© Stack Overflow or respective owner