views:

22

answers:

1

So i have one model with list of all item i have. And other model which has Foreign-Key to to my main model... How to Make query set object. Of all items from first model which contain my second model?

class Music(models.Model):
    name=models.CharField()
    duration=models.IntegerField()


class Playlist(models.Model):
    misic=models.ForeignKey(Music)

How to Make query set obj of Music which is in Playlist? Then iwant to make .aggregate to count duration of all playlist.

+1  A: 

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

  1. 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.
  2. 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.

Manoj Govindan
Music model has not attribute playlist ...
Pol
@Pol: updated my answer. See above.
Manoj Govindan
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....
Pol
@Pol: updated my answer again. See above.
Manoj Govindan
OK... Thanks... I knew about migration... I just though that there is more simple way.... without changing the model of Playlist... Ok i will do counting in circle... Because much work were done.
Pol