On Sun, Oct 15, 2006 at 01:26:18PM -0700, MerMer wrote: > I have two Models. > > 1. Product > 2. Review - There can be many reviews for any product (one -to many > relationship) > > One of the fields of Review is "Rating". This holds an integer between > 1 and 5. > > I want to display a list of Products, and display the average review > rating for each product.
Other responses have pointed you in the direction of custom SQL. There's another (less data-normalized) way, which can be implemented without SQL knowledge: use signals. This also has the benefit of being easily sortable. Step one is to add an "average rating" attribute to your Product model. Set it to default to 0.0, or allow nulls and default to null. Step two is to create a function (a function, not an object method) which will update the average rating. That function should take this argument list: (sender, instance, signal, *args, **kwargs) "instance" is the important one here, as it will be a Review object. Use that to get the Product object, and then calculate the average rating, set the avg_rating attribute of that Product object, and call save(). Step three is wiring that function to the signal you want. Specifically, you probably want the pre_save or post_save signal, fired from the Review model. You can do all of this in your models.py, which would end up looking something like this: # a bunch of imports from django.db.models import signals from django.dispatch import dispatcher class Product: # blah blah blah class Review: # blah blah blah def update_average_rating(sender, instance, signal, *args, **kwargs): # 'instance' will be the Review object being saved # # use that to get the Product object affected, calculate the new # average rating, then call .save() on the Product object dispatcher.connect(update_average_rating, signal=signals.pre_save, sender=Review) Once you do that, the "average rating" attribute in your Product model will be updated automatically every time a new Review is created (or when an old Review is modified). Do a google search for "django signals" for more information. -johnnnnnnnn --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-users -~----------~----~----~----~------~----~------~--~---