1

我想将运行时方法添加到我的 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.pyBuldingTableAdmin.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 可以处理/注册它们吗?

4

1 回答 1

1

您无需在模型中创建字段即可在管理员中显示它。您可以在 ModelAdmin 实体中执行此操作。

class UserAdmin(admin.ModelAdmin):
    list_display = ['username', 'fullname']

    def fullname(self, model):
        return  model.first_name + " " + model.second_name

尽管我们可以动态地向您的模型添加方法。但是你必须把它当作一个方法,而不是一个属性:

def _status(invite):
    if invite.is_activated:
        return "Activated"
    if invite.is_alive:
        return "Live"
    return "Expired"

_status.short_description = 'status'
Invite.status = _status # Invite is model class

这个“属性”通常显示在 admin 和 Django 模板中。

于 2012-10-07T14:57:37.833 回答