ModelAdmin排序?

时间:2011-04-24 22:02:25

标签: django sorting modeladmin

使用Django Admin界面,您如何确保HTML select multiple中的对象按某种顺序排序(更喜欢按字母顺序排列)?问题是我有3个型号 - CD,Song,Singer。一个CD管理仪表板,Song是内联CD和Singer是一个很多领域,我想分类!

我的model.py文件:

class CD(models.Model):

    cd_name = models.CharField("CD Name",max_length=50)
    date = models.DateField("CD Release Date")
    photo = models.ImageField("CD Cover",blank=True,upload_to='covers')
    singers = models.ManyToManyField(Singer,blank=True,null=True) 

    def __unicode__(self):
        return self.cd_name

class Song(models.Model):

    cid = models.ForeignKey(CD)
    track_num = models.PositiveIntegerField("Track Number",max_length=2) 
    song_name = models.CharField("Song Name",max_length=50)
    soloists = models.ManyToManyField(Singer,blank=True,null=True) 
    stream_url = models.URLField("Stream URL", blank=True)

    def __unicode__(self):
        return self.song_name

class Singer(models.Model): (not relevent)

我的admin.py文件:

class SongInline(admin.TabularInline):
    model = Song
    extra = 0

class CDAdmin(admin.ModelAdmin):

    list_display = ('cd_name', 'date')

    inlines = [
        SongInline,
    ]

admin.site.register(CD, CDAdmin)

1 个答案:

答案 0 :(得分:2)

formfield_for_manytomany

class SongInline(admin.TabularInline):
    model = Song
    extra = 0

    def formfield_for_manytomany(self, db_field, request, **kwargs):
            if db_field.name == "soloists":
                kwargs["queryset"] = Singer.objects.order_by('last_name')
            return super(SongInline, self).formfield_for_manytomany(db_field, request, **kwargs)

这回答了您对“ModelAdmin Ordering”的具体问题,但在您的情况下,您可以通过模型ordering模型元类选项简单地为m2m模型定义默认排序。

http://docs.djangoproject.com/en/dev/ref/models/options/#ordering

class Singer(models.Model):
    # my model
    class Meta:
        ordering = ['name'] # your select box will respect this as well.