首页 > 解决方案 > 如何按字母顺序排列多对多字段?

问题描述

我有一个在 models.py 中定义的对象播放列表:

class Playlist(models.Model):
    """Allow a user to create a customized list of songs."""
    name = models.CharField(max_length=100)
    image = models.ImageField(upload_to='playlists/%Y/%m/%d', blank=True, null=True)
    songs = models.ManyToManyField('Song')
    description = models.TextField(blank=True, null=True, max_length=1000)
    date_added = models.DateTimeField(auto_now_add=True)

def __str__(self):
    """String for representing the model object."""
    return self.name

def get_absolute_url(self):
    """Returns the url to access a detail record for this song."""
    return reverse('playlist-detail', args=[str(self.id)])

我也有继承自该模型的 AddNewPlaylist 表单:

class AddPlaylistForm(forms.ModelForm):

    class Meta:
        model = Playlist
        fields = ['name', 'image', 'description', 'songs']

我只希望表单中的“歌曲”对​​象按字母顺序排列,因为它出现在表单中 - 我该怎么做?

编辑:我不想更改song模型在数据库中的排序 - 只是它在 AddPlayList 表单中的排序方式。

标签: django-modelsdjango-formsdjango-2.1

解决方案


所以,我假设在您的 中models.py,您有一个名为Song. 在Song模型中,我假设您有一个 fieldsong_name或类似的东西。在Song中,添加:

class Meta:
    ordering = ('song_name',)

这将按Song名称的字母顺序对所有对象查询集进行排序,包括manytomany播放列表的实例。

如果您想专门订购manytomany而不是所有 Song 查询集,那么您应该创建一个through模型,如下所示:

class PlaylistSong(models.Model):
    playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE)
    song = models.ForeignKey(Song, on_delete=models.PROTECT)

    class Meta:
        ordering = ('song__song_name',)

然后,您可以将songs字段替换为Playlist

songs = models.ManyToManyField(Song, through='PlaylistSong', blank=True)

推荐阅读