Hi all,

I stole some code from this posting:
http://groups.google.com/group/django-users/msg/82a9c2e94ff05188

And then I used it to calculate the rating averages of my songs like
so:



models.py:
=======

class Song(models.Model):
    ...
    songrtng = models.ManyToManyField(Rating)
    ...

class Rating(models.Model):
    ...
    score = models.IntegerField(default=0)
    ...



views.py:
======

songlist = Song.objects.all().extra(
                select={
                    'avg': 'SELECT AVG(song_rating.score) FROM
song_rating \
                     WHERE song_rating.song_id = song_song.id \
                     AND song_rating.score IS NOT NULL',
                 }
)



 template:
=======

{% for currentsong in songlist %}{{ currentsong.id }}:
{{ currentsong.avg }}<br>{% endfor %}



This works beautifully. It's cool when I want the avg rating score for
each song in a certain queryset.
My prob now is that when I already have a specific song (i.e., not
just a subset of songs filtered from all songs), I still need to use
songlist first, filter it down to my specific song's id via id__exact
and take the index [0], and only then its avg. Of course this also
works, but I feel kinda dumb using it that way, so...:

My question is: isn't there a more straight-forward way? I mean, I
know Django has no aggregation support, but still, even with custom
SQL, there must be a DRYer cleaner more elegant way get the rating
score average at the level of an individual song.

If a already have the song instance, I have no idea how to the
respective SQL on it to get what I want since the extra() stuff works
on queries.

Any help greatly appreciated!

EE
--~--~---------~--~----~------------~-------~--~----~
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?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to