我想将运行时方法添加到我的 django 模型中,以便可以通过管理界面查看。感觉:用户应该能够添加一个 CalculationRule 并且应用规则会出现一个“虚拟”表。
# model.py
from django.db import models
import types
def rule(self):
return 12 * self.calorific_requirement
class BuildingTable(models.Model):
building_nr = models.IntegerField()
square_meter = models.FloatField()
calorific_requirement = models.FloatField()
@staticmethod
def __new__(cls, *args, **kwargs):
setattr(cls, "rule", types.MethodType(rule, cls))
return models.Model.__new__(cls, *args, **kwargs)
def reqirement_per_m2(self): # this is also a rule!
return self.calorific_requirement / self.square_meter
def __unicode__(self):
return "Building " + str(self.building_nr)
class CalculationRule(models.Model):
name = models.CharField(max_length=200)
rule = models.CharField(max_length=200)
def __unicode__(self):
return str(self.name)
但是,如果我将“规则”添加到我admin.py
的BuldingTableAdmin.list_display[4], 'rule' is not a callable or an attribute of 'BuldingTableAdmin' or found in the model 'BuildingTable'.
# admin.py
from calccols_app.models import BuildingTable, CalculationRule
from django.contrib import admin
class BuldingTableAdmin(admin.ModelAdmin):
list_display = ["building_nr", "square_meter", "calorific_requirement", "reqirement_per_m2", "rule"]
admin.site.register(BuildingTable, BuldingTableAdmin)
admin.site.register(CalculationRule)
我BuildingTable
在 django 的 shell 中测试过;- 方法存在,但rule
不能正常工作。有什么想法可以注入方法,以便 django 可以处理/注册它们吗?