有如下Model
欲在Buy对象的admin的change_list页面中显示from_people和to_people的名称,应该怎么做呢?
[img]http://dl.iteye.com/upload/picture/pic/74156/ec2cbe61-50f9-3596-9b45-c21f82f844bf.jpg[/img]
找到的定制方法如下:
admin.py
#admin.py end
按照上面的方法修改后,change_list页面中的显示为:
[img]http://dl.iteye.com/upload/picture/pic/74158/a889fcd8-1c58-35c5-a957-9c7483a60d9f.jpg[/img]
from django.db import models
from django.utils.encoding import force_unicode
# Create your models here.
class People(models.Model):
name = models.CharField(max_length = 200)
def __unicode__(self):
return force_unicode(self.name)
class Buy(models.Model):
from_people = models.ForeignKey(People, related_name = 'sale')
to_people = models.ForeignKey(People, related_name = 'buyer')
price = models.IntegerField()
def __unicode__(self):
return force_unicode(u'%s-%s-%s' % (self.from_people, self.to_people, self.price))
欲在Buy对象的admin的change_list页面中显示from_people和to_people的名称,应该怎么做呢?
[img]http://dl.iteye.com/upload/picture/pic/74156/ec2cbe61-50f9-3596-9b45-c21f82f844bf.jpg[/img]
找到的定制方法如下:
admin.py
import django.contrib.admin.sites as djsite
import django.contrib.admin.options as djopt
from django.utils.encoding import force_unicode
from django.db.models.fields.related import RelatedField
import models as mym
def normal_format(val):
return force_unicode(u'%s' % val)
def make_func(model, admin_order_field, format_fun = normal_format,
short_description = None, allow_tags = False,
use_self = False):
lst = admin_order_field.split('__')
def func_internal(self, obj = None):
if not use_self:
obj = self
s = ''
for s in lst:
obj = getattr(obj, s, None)
if not obj:
return force_unicode(admin_order_field)
return format_fun(obj)
if not short_description:
i = 0
while i < len(lst):
s = lst[i]
i += 1
model = model._meta.get_field_by_name(s)[0]
if isinstance(model, RelatedField):
model = model.rel.to
short_description = model.verbose_name
func_internal.short_description = short_description
func_internal.allow_tags = allow_tags
func_internal.admin_order_field = admin_order_field
return func_internal
class PeopleModelAdmin(djopt.ModelAdmin):
list_display = ['name']
class BuyModelAdmin(djopt.ModelAdmin):
saler_name = make_func(mym.Buy, 'from_people__name')
buyer_name = make_func(mym.Buy, 'to_people__name')
list_display = [saler_name, buyer_name, 'price']
djsite.site.register(mym.People, PeopleModelAdmin)
djsite.site.register(mym.Buy, BuyModelAdmin)
#admin.py end
按照上面的方法修改后,change_list页面中的显示为:
[img]http://dl.iteye.com/upload/picture/pic/74158/a889fcd8-1c58-35c5-a957-9c7483a60d9f.jpg[/img]