Django Order By Date, but have “None” at end?

后端 未结 5 1292
半阙折子戏
半阙折子戏 2020-12-05 01:32

I have a model of work orders, with a field for when the work order is required by. To get a list of work orders, with those that are required early, I do this:

5条回答
  •  抹茶落季
    2020-12-05 02:22

    This was not available when the question was asked, but since Django 1.8 I think this is the best solution:

    from django.db.models import Coalesce, Value
    long_ago = datetime.datetime(year=1980, month=1, day=1)
    Work_Order.objects.order_by('dateWORequired')
    MyModel.objects.annotate(date_null=
        Coalesce('dateWORequired', Value(long_ago))).order_by('date_null')
    

    Coalesce selects the first non-null value, so you create a value date_null to order by which is just dateWORequired but with null replaced by a date long ago.

提交回复
热议问题