How to Make query set obj of Music which is in Playlist?
Something like this.
playlist = Playlist.objects.get(**conditions)
music = Music.objects.filter(playlist = playlist)
Then iwant to make .aggregate to count duration of all playlist.
Use a Django annotation with the Sum
class (django.db.models).
from django.db.models import Sum
qs = Music.objects.filter(playlist = playlist).annotate(total =
Sum('duration'))
Update
(After reading @Pol's comment)
Music model has not attribute playlist ...
- Are you getting an error? If so post the code you used and stack trace. I tested out your models locally and the above given filter/annotation worked fine.
- Your models don't make sense to me. I'd expect
Music
and Playlist
models to have a many to many relationship. Failing which a Playlist
should have many Music
instances associated. I.e. Foreign Key should be inside Music
, not other way round as you have now.
Update 2
(After reading @Pol's comment)
Yep... You right... It has to be many to many.. but it's not... What should i do? And Music is already made big table in database. I just need to add support of playlists....
There is no need to change your Music
model or underlying table. You can add a new model Playlist
with the following structure:
class Playlist(models.Model):
music = models.ManyToManyField(Music)
You can now drop the existing playlist table and execute python manage.py syncdb
. The new table for Playlist
and join tables for many to many will be created.
That said I must add a statutory warning that this is not a good way of managing changes to your models. You will be much better off using a migration tool such as South. South will let you handle migrations much more gracefully, especially when there is data change involved.