有时,我们需要扩展model的filed,比如想为每条记录都附加一个字段。我们可以使用模型自定义方法及python的内建函数property来实现。
参考链接:http://djangobook.py3k.cn/2.0/chapter10/
1. 定义模型如下:
class Confitem(models.Model): """配置项信息""" confsection=models.ForeignKey('Confsection') item=models.CharField(max_length=255) default_value=models.CharField(max_length=255) item_order=models.PositiveIntegerField() comment=models.CharField(max_length=1000, null=True, blank=True) detail_desc=models.CharField(max_length=10000, null=True, blank=True) def __unicode__(self): return "%s | %s" % (self.confsection,self.item) class ActualConf(models.Model): """各组件的实际配置""" deploy=models.ForeignKey('Deploy') confitem=models.ForeignKey('Confitem') actual_value=models.CharField(max_length=255) deploy_comment=models.CharField(max_length=1000, null=True, blank=True) def _get_section(self): section = self.confitem.confsection return section section = property(_get_section)
其中自定义的_get_section方法返回confitem的外键的外键。
2. 修改视图admin.py中以显示这个新字段 #以下1个类定义ActualConf的管理界面 class ActualConfAdmin(admin.ModelAdmin): list_display = ['deploy', 'section', 'confitem', 'actual_value'] list_filter = ('deploy', 'confitem') list_editable = ['actual_value'] search_fields = ['confitem', 'actual_value']
3. 在list_display加入‘section’,就能在页面上显示这个字段了——但这个字段不能被过滤器识别,加在list_filter中会出错。
附加入扩展字段前、后两张图: