如何在ManyToManyField中搜索相关项目?

时间:2010-02-27 21:47:17

标签: django django-models

实际上有这个模型:

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)
如果X MusicFile在Y播放列表中,

MusicFile.exist_in_playlist会返回我。

  1. 使用django,我可以选择写PlayList.items.exist(MusicFile)之类的内容吗?

  2. 如果没有,如果MusicFile在播放列表中,这是一个很好的搜索实现吗?

  3. 感谢。

2 个答案:

答案 0 :(得分:4)

您可以像这样简化(在1.2中添加了exists()):

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

答案 1 :(得分:1)

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

或从另一方

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

请参阅documentation about accessing related objectsmore examples of making queries using Many to Many relationships