Best way to make a simple orderable playlist in django

£可爱£侵袭症+ 提交于 2019-12-06 12:08:38

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