Hmm... this is slightly different... is BookRatings and Books 1 to 1?
If I store these aggregates as part of the class that it's grouping
by. Here's how I do it for restaurants:
class RestaurantRating(models.Model):
restaurant = models.ForeignKey(Restaurant)
value = models.IntegerField(null=True, blank=True)
user = models.ForeignKey(Profile)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = u'restaurant_rating'
def save(self, force_insert=False, force_update=False):
try:
super(RestaurantRating, self).save(force_insert,
force_update)
cursor = connection.cursor()
query = "SELECT count(value), avg(value) FROM
restaurant_rating WHERE restaurant_id = %s"
results = cursor.execute(query, (self.restaurant.id,))
for row in cursor.fetchall():
self.restaurant.num_ratings = row[0]
self.restaurant.average_rating = row[1]
self.restaurant.save()
except:
transaction.rollback()
else:
transaction.commit()
It's worked well for me, although I haven't used this in production
yet. Let me know if this works for you.
On Dec 26, 4:48 pm, eldonp2 <[email protected]> wrote:
> Is there a way to calculate and store the average rating in this
> example:
>
> RATING_CHOICES = {
> '3' : 'Excellent',
> '2' : 'Good',
> '1' : 'Poor',
>
> }
>
> class Loan(....
> ...
> book = models.ForeignKey(Book)
> rating = models.IntegerField(choices=RATING_CHOICES)
> ...
>
> class BookRatings(...
> ...
> book = models.ForeignKey(Book)
> rating = models.IntegerField(...here I would like the average rating
> from the Loan model...)
> nums = models.IntegerField(...and here the number of ratings
> done...)
> ...
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---