django属性字段verbose name设置

django 中的计算字段可以通过@property来标识,然后可以在list_display属性在列表中显示出来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Yun_Order(models.Model):
name = models.CharField(_('Order No'),max_length=50,unique=True)
device_id = models.ForeignKey('Yun_Device',verbose_name=_('Device ID'))
date_start = models.DateTimeField(_('Start Time'))
date_stop = models.DateTimeField(_('End Time'),null=True)
user_id = models.ForeignKey('Yun_User',verbose_name=_('User ID'))
order_time = models.CharField(_('Last Time'),max_length=50,blank=True,default=0)
state = models.CharField(_('Status'),choices=STATES,max_length=50,default='progess')
ble_deviceId = models.CharField(_('BLE Device ID'),max_length=50,blank=True)
ble_serviceId= models.CharField(_('BLE WXSR ID'),max_length=50,blank=True)
prepay_id = models.CharField(_('WX PAY PRE ORDER'),max_length=100,blank=True)
close_method = models.CharField(_('Close Method'),choices=CLOSEMETHOD,max_length=50,blank=True)
@property
def amount(self):
if self.state != 'progress':
timestamp = self.date_stop - self.date_start
return timestamp.total_seconds() * 0.001
else:
return 0
#amount.short_description = _('Amount')

在admin中:

1
list_display = ('name','device_id','date_start','date_stop','user_id','order_time','state',Yun_Order.amount,'close_method')

但是这里有一个问题,list中默认显示的是Amount,怎么能修改amount这个字段的显示名字呢?
我们需要先去掉amount方法的@property装饰,为什么?因为如果被property装饰了,会报以下错误:
AttributeError: 'property' object has no attribute 'short_description'
按照如下代码修改:

1
2
3
4
5
6
7
8
9
@property
def amount(self):
if self.state != 'progress':
timestamp = self.date_stop - self.date_start
return timestamp.total_seconds() * 0.001
else:
return 0
amount.short_description = _('Amount')

这样就可以显示出verbose name来了。

效果如下