格式化Django的horizo​​ntal_filter选项

时间:2016-08-03 21:59:34

标签: django django-admin

下面的代码有效,除了B类的字段name3和name4在filter_horizo​​ntal中连接在一起。我的问题如何格式化name3和name4?例如,如果name3 ='a',name4 ='b',则显示filter_horizo​​ntal 'a b'。如何将其格式化为'b(a)'之类的内容?

model.py

class A(models.Model):
    name1 = models.CharField(max_length=32)
    name2 = models.ManyToManyField('B')

class B(models.Model):
    name3 = models.CharField(max_length=15) 
    name4 = models.CharField(max_length=100)
=============================
admin.py 

from django.contrib import admin
from .models import A,B

class AAdmin(admin.ModelAdmin):
    fields = [ 'name1', 'name2'] 
    filter_horizontal = ('name1','name2')

admin.site.register(A, AAdmin)

1 个答案:

答案 0 :(得分:2)

以下是您的操作方法:

class AAdmin(admin.ModelAdmin):
    fields = [ 'name1', 'formatname2'] 
    filter_horizontal = ('name1','formatname2')

    def formatname2(self, obj):
        return "{0} ({1})".format(obj.name2.name4, obj.name2.name3)