0
votes

I am using django annotate to display to users the rating and number of reviews for a certain place. I have three models to do this:

class Descriptions(models.Model):
    name=models.CharField(max_length=50)
    website=models.CharField(max_length=50,blank=True)
    street1=models.CharField(max_length=50,blank=True)
    street2=models.CharField(max_length=50,blank=True)
    city=models.CharField(max_length=50,blank=True)
    state=models.CharField(max_length=50,blank=True)
    zip=models.CharField(max_length=5,blank=True)
    description=models.TextField()
    areas_related=models.TextField()
    add_area=models.CharField(max_length=50,blank=True)
    federal=models.NullBooleanField(null=True)
    lat=models.TextField(blank=True)
    long=models.TextField(blank=True)
    creator=models.ForeignKey(User)

    def __unicode__(self):
        return u'%s %s %s %s %s %s %s %s %s %s %s %s %s' %(self.name,self.website,self.street1,
        self.street2,self.city,self.state,self.zip,self.description,self.add_area, self.federal, self.lat, self.long, self.creator)

for the places. Then I have:

class Rating(models.Model):
    rating=models.IntegerField(blank=True)
    place=models.ForeignKey(Descriptions)

    def __unicode__(self):
        return u'%s %s' %(self.rating, self.place)

for the ratings. And finally:

class Review(models.Model):
    user=models.ForeignKey(User)
    place=models.ForeignKey(Descriptions)
    review=models.TextField(blank=True)

    def __unicode__(self):
        return u'%s %s %s' % (self.user, self.place, self.review)

And I am using this to get the places, along with ratings and reviews:

relevant=Descriptions.objects.annotate(Avg('rating')).annotate(Count('review'))

... However, I have a ratings system of 1 to 5. When I input a rating, I get a value of 16 for avg, which then increases by .5 a new rating is added. Also, the count for review increases by 3 every time I add a rating. So, something strange is going on, but I'm not sure exactly what it is, especially considering that number of reviews increases by 3 for any value of rating I put in... Any help would be appreciated.

1

1 Answers

0
votes

Try:

relevant=Descriptions \
    .objects \
    .annotate(average_rating = Avg('rating__rating')) \
    .annotate(review_count = Count('review'))

Currently you are getting the average of the number of ratings objects, not the average number of rating values for each of those objects