Django:添加“NULLS LAST"查询 [英] Django: Adding "NULLS LAST" to query

查看:34
本文介绍了Django:添加“NULLS LAST"查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Postgresql 的NULLS LAST"选项对模型进行排序.怎么可能做到?

I would like to sort a model by using Postgresql's "NULLS LAST" option. How could it be done?

我尝试过类似的东西

MyModel.objects.all().extra(order_by=('-price', 'NULLS LAST'))

但是我明白了

无法将关键字 'NULLS LAST' 解析为字段"

"Cannot resolve keyword 'NULLS LAST' into field"

推荐答案

from django.db.models import F  
MyModel.objects.all().order_by(F('price').desc(nulls_last=True))

此功能已添加到 Django 1.11.

This functionality has been added to Django 1.11.

https://docs.djangoproject.com/en/dev/releases/1.11/

将 nulls_first 和 nulls_last 参数添加到 Expression.asc()和 desc() 来控制空值的顺序.

Added the nulls_first and nulls_last parameters to Expression.asc() and desc() to control the ordering of null values.

Django 3.1 参考:https://docs.djangoproject.com/en/3.1/ref/models/expressions/#using-f-to-sort-null-values

Reference for Django 3.1: https://docs.djangoproject.com/en/3.1/ref/models/expressions/#using-f-to-sort-null-values

这篇关于Django:添加“NULLS LAST"查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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