how to search related items into ManyToManyField?
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.
With django do I have the option to write something like
PlayList.items.exist(MusicFile)
?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.
精彩评论