Ordering a Django queryset by the returned results of a method

后端 未结 2 1497
悲哀的现实
悲哀的现实 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('<date field>') - timezone.now())  # some computation
    ).order_by('thing_date')
    
    0 讨论(0)
  • 2020-12-16 13:11

    If thing_date() is a function in python code, you can't get the database to sort on it. Which means it doesn't make sense to put the queryset. You'll have to sort the results after you get them into python. This will be fine so long as you're not dealing with a very large number of objects.

    qs = Things.objects.filter(user='Bill')
    unsorted_results = qs.all()
    sorted_results = sorted(unsorted_results, key= lambda t: t.thing_date())
    

    If you've got a very large number of Things then you'll have to figure some way to get thing_date into the database or else you'll have memory issues.

    0 讨论(0)
提交回复
热议问题