实际上有这个模型:
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
会返回我。
使用django,我可以选择写PlayList.items.exist(MusicFile)
之类的内容吗?
如果没有,如果MusicFile在播放列表中,这是一个很好的搜索实现吗?
感谢。
答案 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 objects和more examples of making queries using Many to Many relationships。