Django: ORDER BY DESC on FloatField puts null values top?
I'm surprised to find that an ORDER BY DESC query on a FloatField in Django returns null fields higher than fields with positive values.
# In models.py
class City(models.Model):
name = models.CharField(max_length=30)
country = models.ForeignKey(Country)
value = models.FloatField(null=True开发者_如何学运维, blank=True)
# In views.py
cities = City.objects.filter(country__id=country.id).order_by('-value')
# In template.html
{% for city in cities %}{{ city.name }}: {{ city.value }} --{% endfor %}
I get back the following:
London: None -- Paris: None -- Berlin: 84.0 -- Tunis: 15.0 --
Instead, I want to return all the entries in descending order, with the None values last (i.e. Berlin, Tunis, London, Paris). Any way to do this?
I think Django doesn't make any assumption about ordering of NULLs. Different SQL databases handle that ordering differently - SQLite/MySQL put NULLs at the top, Oracle at the bottom (for ascending ORDER BY clauses). So that's probably a problem with Django not "abstracting away" these differences.
But in most use cases, it doesn't make sense to include NULLs in sorted query results. If you really have a use case where you need it, you should probably sort manually (i.e. after making the query).
精彩评论