views:

40

answers:

2

Actually have this model:

class MusicFile(models.Model):
    file = models.FileField(upload_to="files")

    def exist_in_playlist(self, playlist_id):
        exist = False
        try:
            mp = PlayList.objects.get(id=playlist_id, items__id=self.id)
            exist = True
        except PlayList.DoesNotExist:
            pass
    return exist

class PlayList(models.Model):
    items = ManyToManyField(MusicFile)

MusicFile.exist_in_playlist returns me if X MusicFile is in Y Playlist.

  1. With django do I have the option to write something like PlayList.items.exist(MusicFile) ?

  2. If not, Is this a good implementation for search if a MusicFile is in the PlayList?

Thanks.

+1  A: 
if MusicFile.objects.filter(playlist=playlist_id).count() > 0:
    ...

or from the other side

if PlayList.objects.filter(musicfile=musicfile_id).count() > 0:
    ...

See documentation about accessing related objects, and more examples of making queries using Many to Many relationships.

Ludwik Trammer
+2  A: 

You can simplify that like this (exists() was added in 1.2):

def exist_in_playlist(self, playlist):
    return self.playlist_set.filter(pk=playlist).exists()
Dmitry Shevchenko