开发者

how to search related items into ManyToManyField?

开发者 https://www.devze.com 2022-12-21 06:05 出处:网络
Actually have this model: class MusicFile(models.Model): file = models.FileField(upload_to=\"files\") def exist_in_playlist(self, playlist_id):

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.


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()


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消