django 1.2 change_list 中显示ForeignKey中的列

有如下Model

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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值