On 10/15/06, MerMer <[EMAIL PROTECTED]> 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.
>
> I can see how I can easily display the number of reviews for each
> product by using
> "review_set.count"  but it's not clear to me how I go about displaying
> the average rating.
>
> Could anybody set me on the right path on this?  I'm sure it must be a
> common type of requirement.  I'm very new to both Python and Django.
>
> MerMer

The following should give each Product a "rating" attribute containing
the average rating - you'll need to change the table names to match
whatever you have, and you can omit the NOT NULL condition if ratings
are mandatory for your review table.

Product.objects.all().extra(
    select={
        'rating': 'SELECT AVG(appname_review.rating) FROM
appname_review WHERE appname_review.product_id = appname_product.id
AND appname_review.rating IS NOT NULL',
    }
)

The AVG function may be database dependent - I ran this on sqlite to test it.

Jonathan.

--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to