Django:按位置排序忽略NULL [英] Django : Order by position ignoring NULL

查看:106
本文介绍了Django:按位置排序忽略NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的模型包含一个名为位置的字段(a PositiveSmallIntegerField ),我想用来订购查询结果。



我使用 order_by('position') ,这非常有用。



问题:我的位置字段为空( null = True,blank = True ),因为我不会为我的模型的每50000个实例指定一个位置: p>

当某些实例具有NULLposition时, order_by 返回列表顶部:我想他们要结束...



在RAW SQL中,我曾经写过 IF(position IS NULL or position =' ',1,0)(请参阅 http: //www.shawnolson.net/a/730/mysql-sort-order-with-null.html ):是否可以使用Django获得相同的结果,而无需写入原始SQL?



非常感谢!

解决方案

请使用 django agrregation 中的annotate()来执行以下操作:

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


I have a problem with django queryset ordering.

My model contains a field named position (a PositiveSmallIntegerField), which I'd like to used to order query results.

I use order_by('position'), which works great.

Problem : my position field is nullable (null=True, blank=True), because I don't wan't to specify a position for every 50000 instances of my model :(

When some instances have a NULL "position", order_by returns them in the top of the list : I'd like them to be at the end...

In RAW SQL, I used to write things like "IF(position IS NULL or position='', 1, 0)" (see http://www.shawnolson.net/a/730/mysql-sort-order-with-null.html) : is it possible to get the same result using Django, without writing raw SQL ?

Thanks very much !

解决方案

You can use the annotate() from django agrregation to do the trick:

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

这篇关于Django:按位置排序忽略NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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