我在Django的dynamic model中調用property()
時遇到問題。我需要一個額外的字段,它給了我一個數據庫表的現有字段的對數轉換值。爲了進一步處理,該字段必須可通過模型結構訪問。數據庫表的名稱將在運行時定義,以便我需要一個動態模型。如何在動態Django模型中調用屬性方法?
這是我的模型定義:
def create_model(self, name, libs=None, app_label='gotool', module='', options=None, admin_opts=None):
fields = {
'database_id': models.CharField(max_length=255, primary_key=True),
'description': models.TextField(blank=True),
'l1_normalized': models.FloatField(null=True, blank=True),
'l2_normalized': models.FloatField(null=True, blank=True),
'pvalue': models.FloatField(null=True, blank=True),
'log2fc': models.FloatField(null=True, blank=True),
'goterm': models.TextField(db_column='GOTerm', blank=True),
'_get_l1_logcount': lambda self: numpy.log10(self.l1_normalized),
# here is my problem:
'l1_s_logcount': property(_get_l1_logcount), # I don't know how to call the property-method inside the dynamic model definition
}
class Meta:
pass
if app_label:
setattr(Meta, 'app_label', app_label)
if options is not None:
for key, value in options.iteritems():
setattr(Meta, key, value)
attrs = {'__module__': module, 'Meta': Meta}
if fields:
attrs.update(fields)
model = type(name, (models.Model,), attrs)
if admin_opts is not None:
class Admin(admin.ModelAdmin):
pass
for key, value in admin_opts:
setattr(Admin, key, value)
admin.site.register(model, Admin)
return model
非常感謝您的幫助!