Django:按位置排序忽略 NULL

标签 django sql-order-by nullable

我对 Django 查询集排序有疑问。

我的模型包含一个名为 position 的字段,一个 PositiveSmallIntegerField,我想用它来对查询结果进行排序。

我使用 order_by('position'),效果很好。

问题:我的position 字段可以为空(null=True, blank=True),因为我不想为我的模型的每 50000 个实例指定一个位置。当某些实例具有 NULL position 时,order_by 将它们返回到列表的顶部:我希望它们位于末尾。

在原始 SQL 中,我曾经写过这样的东西:

IF(position IS NULL or position='', 1, 0)

(参见 http://www.shawnolson.net/a/730/mysql-sort-order-with-null.html)。是否可以在不编写原始 SQL 的情况下使用 Django 获得相同的结果?

最佳答案

您可以使用 django agrregation 中的 annotate()做这个把戏:

items = Item.objects.all().annotate(null_position=Count('position')).order_by('-null_position', 'position')

关于Django:按位置排序忽略 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5235209/

相关文章:

django - 如何在 django 中缓存模型方法?

python - django,fastcgi : how to manage a long running process?

mysql - 如果第一行将被随机化,其余行应按标准排序,如何选​​择行

c# - LINQ OrderBy 查询

python - 在 Django 中使用 shell

django - 如何使用 djangorestframework 更新 ImageField/FileField?

php - 计算来自 2 个 MySQL 表的行 JOIN 与第 3 和 ORDER BY 最高计数结果

c# - 可空引用类型 : How to specify "T?" type without constraining to class or struct

c# - Json.Net 无法从动态对象反序列化为 nullable<short>

c# - 转换int吗?有条件地