Ordering a Django queryset by the returned results of a method

后端 未结 2 1509
悲哀的现实
悲哀的现实 2020-12-16 12:14

Let\'s say I have a queryset of things Bill has worked on like this:

test=Things.objects.filter(user=\'Bill\')

Now I want to sort all those

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 13:07

    see these answers to use a computed value to sort a QuerySet:

    • how to sort by a computed value in django
    • Order a QuerySet by aggregate field value

    Basically if thing_date() can be determined using a query expression, then you can use it to annotate and search the query set.

    from django.db.models import F
    from django.utils import timezone
    test = Things.objects.filter(user='Bill').annotate(
        thing_date=(F('') - timezone.now())  # some computation
    ).order_by('thing_date')
    

提交回复
热议问题