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'
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With