Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

@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?

like image 772
Michael Place Avatar asked May 01 '13 16:05

Michael Place


People also ask

What does .all do in Django?

Definition of the all() manager method: all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result.

What does .values do in Django?

values() Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.

What is first () in Django?

first, which takes a query set and returns the first element, or None if the query set was empty. Instead of writing this: try: object = MyModel.objects.get(key=value) except model.DoesNotExist: object = None.


2 Answers

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

sorted(MyModel.objects.all(),  key=lambda m: m.calculate_rating)
like image 171
Alexandre Avatar answered Oct 12 '22 04:10

Alexandre


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: https://stackoverflow.com/a/981802/1869597

like image 36
Jordan Jambazov Avatar answered Oct 12 '22 06:10

Jordan Jambazov