我对 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/