Wednesday, March 18, 2015

Re: Django Query to get max rating

From what I could understand, you are trying to fetch all the top ratings for each question in a group, correct?

The problem is that this query:

top_rated_list = Ratings.objects.get(rating = max_rating)

is returning more than one rating instance. "get" queries are supposed to return a single result, if you need more than one, you should be using a "filter" query.

This is happening because there are more than one rating with a max_rating in your database. What i think you really meant to be doing is to fetch the best for rating for a single question, so your query would look like this:

top_rated_list = Ratings.objects.get(rating = max_rating, question=i)

But, this can also lead to the same error when two users give a question the same rate.
In this case, if it doesn't mater if you pick one or the other, a fix for this can be:

top_rated_list = Ratings.objects.filter(rating = max_rating, question=i).first()

Now, the way you are doing this, the "top_rated_list" will only have one rating object everytime. To return a list of ratings, you should appending to the list:
question_top_rate =  Ratings.objects.filter(rating = max_rating, question=i).first()  top_rated_list.append(question_top_rate)  
Also, the way you are modelling the relationships, there is a many to many relationship from a Group to a Question, so a question belongs to multiple groups. If this is the behaviour you are looking for, you should be using a ManyToManyField as documented here:
also, take a look in the "through" parameter:
It what your really wanted was to a question belong to a single group, it would make more sense to have a ForeignKey to Group in the Question model.

You can also optimize the way you are doing the queries, but that's another topic.
--
  
Filipe Ximenes
+55 (81) 8245-9204
Vinta Software Studio
http://www.vinta.com.br

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAA-QWB0c%2B-u4KS%3D8rJARQsOhJpQK84B1C_NOc_zV2ErUq2FaeQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment