Ashuosh Mishra
Ashuosh Mishra

Reputation: 27

Calculate Average rating of 5 star rating

i want to get average of all ratings related to user

class UserRating(models.Model):

User_Name=models.ForeignKey(MyUser,on_delete=models.CASCADE)
Rating = models.IntegerField(
    default=1,
    validators=[MaxValueValidator(5), MinValueValidator(1)]
 )

def __str__(self):
    return str(self.User_Name)

class UserRatingViewSet(viewsets.ViewSet):

def create(self,request):
    try:
        User_Name=request.data.get('User_Name')
        Rating=request.data.get('Rating')
        new=UserRating()
        new.User_Name=MyUser.objects.get(user_name=User_Name)
        new.Rating=Rating
        new.save()

        return Response({"Data":"Delivered"})
    except Exception as error:
        return Response({"message":str(error),"success":False})

def list(self,request):
    ashu=UserRating.objects.all()
    print(ashu)
    a=[]
    for  i in ashu:
        a.append({
            "User_Name":i.User_Name.user_name,
            "Rating":i.Rating,
        })
    return Response({"message":a})

Upvotes: 1

Views: 943

Answers (2)

Hagyn
Hagyn

Reputation: 962

To get a list of all the averages per each user you can do:

from django.db.models import Avg
user_ratings = UserRating.objects.all().values('User_Name').order_by('User_Name').annotate(rating_average=Avg('Rating'))

Using a for is not recommendable, this way the performence is better cause it is directly done in the database.

Upvotes: 1

Pruthvi Barot
Pruthvi Barot

Reputation: 2018

ashu = UserRating.objects.all()
dict = {}
for line in ashu:
    if dict.get(line.User_Name.user_name):
        dict[line.User_Name.user_name] = (dict[line.User_Name.user_name] + line.Rating)/2
    else:
        dict.update({line.User_Name.user_name:line.Rating})
print(dict)

like this?

Upvotes: 0

Related Questions