本文介绍了在Django中制作简单的可订购播放列表的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的Django orm问题:

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?

我对此表示怀疑,但是如果是这样,我如何获得订购的QuerySet? (我将序列化为json,因此首选QuerySet,但是如果您使用其他简单的制作json的方式,我很想听听!)

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)

但是,根据PlaylistTrack.position字段,这不能保留顺序...

But this doesn't preserve ordering, according to PlaylistTrack.position field...

谢谢!

推荐答案

如果您注意到您的 PlaylistTrack 模型只不过是Many-2-Many中间表,那么事情将会变得更加明显(请检查):

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']

现在您可以这样做:

my_playlist.tracks.all()

这篇关于在Django中制作简单的可订购播放列表的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 23:10