Django order_by a property
I'm faced with a problem wherein I'm trying to create a QuerySet with the results ordered not by a field on a model, but instead ordered by the result of a value returned by a method on the model.
class MyModel(models.Model): someAttributes = models.TextField(blank=True) @property def calculate_rating(self): <do some calculation and return integer>
Given that, how can I construct a QuerySet that orders the results by the value for each instance as returned by calculate_rating()?
In trying to simply use order_by(), I get an error:
Cannot resolve keyword 'average_rating' into field.
Can anybody provide some ideas?
There is no way to do this. One thing you can do is to create a separate database field for that model and save the calculated rating in it. You can probably override the save method of the model and do the calculations there, after that you can only refer to the value.
You can also sort the returned QuerySet using Python sorted. Take into account that the sorting approach using the built-in sorted function increases a lot the computational complexity and it's not a good idea to use such code in production.
For more information you can check this answer: http://stackoverflow.com/a/981802/1869597
order_by is for database stuff. Try to use sorted instead:
sorted(MyModel.objects.all(), key=lambda m: m.calculate_rating)