Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Django style order_by() to sort a list of existing model objects instead of QuerySet?

Is there an easy way to reuse Django-style QuerySet ordering to sort a list of model objects.

Something that would correspond to:

MyModel.objects.all().order_by('-field', 'parent__field')

Only I got a list(MyModel.objects.all()) as input, so I already got all the objects and just need to sort them in memory by '-field', 'parent__field'.

like image 357
serg Avatar asked Oct 30 '22 08:10

serg


1 Answers

As OP mentioned in comments, he has modified the values of the fields to be used for ordering, and now has to reorder the list.

While one can write a simple for-loop/comprehension to order by the required attribute, if you prefer the clean interface of Django ORM, you can use a tool such as the recent lifter to manipulate a collection of objects/dicts in the same way:

import lifter

my_objects = MyModel.objects.all().order_by('-field', 'parent__field')

# ... manipulate my_objects ...

ObjModel = lifter.models.Model('MyModel')
manager = ObjModel.load(my_objects)

results = manager.order_by('-field', 'parent__field')

Note that ordering by related fields (such as parent__field) may not be directly supported (yet?), and you may need to pre-populate that field with the values of the related object.

like image 116
tutuDajuju Avatar answered Nov 11 '22 02:11

tutuDajuju