Best way to make a simple orderable playlist in django
simple django orm question:
I've got a pretty classic example of a playlist and track models:
class Track(models.Model):
name = models.CharField(max_length = 50)
开发者_JAVA百科 mp3 = models.FileField(upload_to="track/")
class Playlist(models.Model):
name = models.CharField(max_length = 50)
class PlaylistTrack(models.Model):
playlist = models.ForeignKey('track.Playlist')
track = models.ForeignKey('track.Track')
position = models.IntegerField() #Here's the crux of the problem
Is this the best way of making an orderable playlist?
I doubt it, but if so, how do I get an ordered QuerySet
? (I will be serialising to json, so a QuerySet
is prefered, but if you have a different, simple, way of making json I'd love to hear it!)
Here's what I have so far:
playlist = Track.objects.filter(playlisttrack__playlist__exact=1)
But this doesn't preserve ordering, according to PlaylistTrack.position
field...
Thanks!
If you notice that your PlaylistTrack model is nothing more than a Many-2-Many intermediate table, then things will become more obvious (check this):
class Playlist(models.Model):
name = models.CharField(max_length = 50)
tracks = models.ManyToManyField('Track', through='PlaylistTrack')
class PlaylistTrack(models.Model):
playlist = models.ForeignKey('track.Playlist')
track = models.ForeignKey('track.Track')
position = models.IntegerField() #Here's the crux of the problem
class Meta:
ordering = ['position']
Now you can just do:
my_playlist.tracks.all()
If its order that you're worried about just add an order_by
clause to the end of your query.
playlist = Track.objects.filter(playlisttrack__playlist__exact=1).order_by('+playlisttrack__position')
To dump the result set to json simply:
json_serializer = serializers.get_serializer("json")()
json_serializer.serialize(playlist, ensure_ascii=False, stream=response)
精彩评论