如何从Django ORM中的PostgreSQL更改默认的空排序行为 [英] How to change default null sorting behavior from PostgreSQL in the Django ORM

查看:303
本文介绍了如何从Django ORM中的PostgreSQL更改默认的空排序行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



您可以修改每个查询的这种行为,或者通过指定NULLS LAST或NULLS FIRST来创建索引。



如何将其与Django ORM结合使用,而不需要使用原始查询?
I.e当我添加到我的query_set像 qs.order_by( - publish_start),如何指定空值的排序?或者,作为替代方案,在字段/索引声明。

解决方案

我想出了一种适应任何一种方式工作的DB引擎(null为最高或最低值)通过使用 extra ,使null检查布尔值,并且当排序布尔值 false<真的似乎是普遍的:

  qs = qs.extra(select = {'null_start' publish_start is null},
order_by = ['null_start','-publish_start'])


PostgreSQL by default considers NULL values as the highest, and thus sorts them first for descending queries and last for ascending ones.

You can modify this behaviour per query or at index creation by specifying 'NULLS LAST' or 'NULLS FIRST'.

How can I use this in conjunction with the Django ORM, without needing to use raw queries? I.e. when I add to my query_set something like qs.order_by("-publish_start"), how can I specify sorting for nulls? Or, as an alternative, upon field/index declaration.

解决方案

I figured out a way that accommodates DB engines that work either way (null as highest or lowest value) by using extra, making the null check a boolean, and when sorting booleans false < true seems to be universal:

qs = qs.extra(select={'null_start': "publish_start is null"},
              order_by=['null_start', '-publish_start'])

这篇关于如何从Django ORM中的PostgreSQL更改默认的空排序行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆