Best way to make a simple orderable playlist in django

ぐ巨炮叔叔 提交于 2019-12-22 12:41:56

问题


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


回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/4799378/best-way-to-make-a-simple-orderable-playlist-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!