Django在运行时添加模型方法

时间:2012-10-07 14:47:06

标签: python django django-models django-admin

我想在运行时方法中添加我的django模型,以便通过admin-interface查看它。 Sense:用户应该能够添加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)

我在django的shell中测试了BuildingTable; rule - 方法存在,但无法正常工作。任何想法如何我可以注入方法,以便django可以处理/注册它们?

1 个答案:

答案 0 :(得分: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-templates中。