Humza
Humza

Reputation: 91

Django order_by Property gives error undefined

i am trying to order by (descending) average_score, but when i run it i get error: name 'average_score' is not defined. What am i doing wrong here?

error: name 'average_score' is not defined

model:

def _get_average_rating(self):
    reviews = Ratings.objects.filter(post=self)
    average = reviews.aggregate(Avg('score'))['score__avg']
    average = round(average, 1)
    return average


average_score = property(_get_average_rating)

view:

if sort == 'Average Rating':

    Posts = Posts.order_by(-average_score)

Upvotes: 0

Views: 239

Answers (3)

Humza
Humza

Reputation: 91

I have found the answer:

By using python's Sorted method like this:

Posts = sorted(Posts, key=lambda x: x.average_score, reverse=True)

Upvotes: 0

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21807

Firstly you cannot use methods in ORM queries. Secondly you get the error because no variable named average_score exists in that scope.

To do what you want you need to bring the logic inside your query instead of trying to use the method.

Post.objects.all().annotate(average_score=Avg('ratings__score')).order_by('-average_score')

Note: Don't sort in python your database can do it more efficiently.

Note: Also Model names should be singular so Rating instead of Ratings

Upvotes: 0

Lars
Lars

Reputation: 1270

Try to use this :-

views.py

Posts = Post.objects.all().order_by('-average_score')

You didn't show your full view. So it is hard to guess if you're using an id to filter objects.

*Note :- .all() will get all the objects from your Post Model.

Upvotes: 1

Related Questions