order_with_respect_to 为反向关系

order_with_respect_to for reverse relationship

假设我有以下模型:

class Playlist(models.Model):
    name = models.TextField()    
    songs = models.ManyToManyField(Song)

class Song(models.Model):
    title = models.TextField()

所以一个播放列表可以有多首歌曲,一首歌曲可以在多个播放列表中。

我想添加一个 "order" 字段,以便用户可以对播放列表中的歌曲重新排序。我发现 order_with_respect_to,这似乎是一个完美的解决方案。但是,我需要将该元选项添加到 Song 模型中,例如:

class Song(models.Model):
    title = models.TextField()

    class Meta:
        order_with_respect_to = 'playlists'

显然,由于我已经在播放列表模型中指定了关系,所以没有在歌曲上指定播放列表字段。有没有办法使用 related_name 指定 order_with_respect_to 的反向关系?或者我可以在歌曲模型中添加对播放列表的 ForeignKey 引用吗?

order_with_respect_to(可以说)在您有 ForeignKey 但不是 ManyToManyField 时很有用。它通过向模型添加一个额外的字段来工作,但在您的情况下,顺序因 Playlist.

而异

在 Django 中执行此操作的直接方法是将订单放在显式创建的 through table.

class Playlist(models.Model): 
    name = models.TextField()
    songs = models.ManyToManyField(Song, through='PlaylistSong')

class Song(models.Model):
    title = models.TextField()

class PlaylistSong(models.Model):
    playlist = models.ForeignKey(Playlist)
    song = models.ForeignKey(Song)
    order = models.PositiveSmallIntegerField()

因此,要以正确的顺序在 Playlist 中获取 Songs,您需要执行以下操作:

Song.objects.filter(playlistsong__playlist_id=1)
            .order_by('playlistsong__order')