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.

To wit:

class MyModel(models.Model):

someAttributes = models.TextField(blank=True)

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:

order_by is for database stuff. Try to use sorted instead:

sorted(MyModel.objects.all(),  key=lambda m: m.calculate_rating)

Need Your Help

windows git https clone through proxy server failed to write files

windows https github clone proxy-server

In the process of cloning a repo through my company proxy server through sysinternal I can see the it tried to write the git repository but failed. However, the .git directory was created but mostl...

Adding error message to Spring 3 DataBinder for custom object fields

spring-mvc bean-validation

I'm trying to manually add an individual email error message to my model but nothing is displaying in the view.