Django: ORDER BY DESC on FloatField puts null values top?

喜欢而已 提交于 2019-12-10 23:49:50

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/4566939/django-order-by-desc-on-floatfield-puts-null-values-top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!