Django: Adding “NULLS LAST” to query

前端 未结 8 2192
时光说笑
时光说笑 2020-11-27 14:25

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

I tried something like

MyModel.objects.all().extra(ord

8条回答
  •  青春惊慌失措
    2020-11-27 14:32

    @kabucey's answer is best for Django >= 1.11, but if you're using at least Django 1.8, 1.9 or 1.10, you can use a custom Func expression to achieve "NULLS Last" behaviour, as described at https://www.isotoma.com/blog/2015/11/23/sorting-querysets-with-nulls-in-django/:

    from django.db.models import Func
    
    class IsNull(Func):
        template = '%(expressions)s IS NULL'
    
    MyModel.objects.all().annotate(
        price_isnull=IsNull('price_isnull'),
        ).order_by(
            'price_isnull',
            '-price',
            )
    

    The first order_by argument sorts the list in ascending order by price_isnull, forcing null-price items to the end of the list since True > False.

提交回复
热议问题