在运行时生成代码

时间:2013-04-18 10:52:13

标签: python django

我需要在运行时根据from值生成下面的模型。

以下是我试图实现的一个例子,但问题很明显,即[field.value] ......

def import_data(form, *args, **kw):
    class ContactCSVModel(CsvModel):  
        for field in form:
           [field.value] =  CharField()

         class Meta:
            delimiter = ","
            dbModel = Contact
            update = {'keys': ["mobile", "group"]}

      return ContactCSVModel.import_data(*args, **kw)

所以上面的代码在生成之后会是这样的(如果它是类型化的静态代码)....

def import_data(form, *args, **kw):
    class ContactCSVModel(CsvModel):  

        first_name = CharField()
        mobile = CharField()
        last_name = CharField()

         class Meta:
            delimiter = ","
            dbModel = Contact
            update = {'keys': ["mobile", "group"]}
  return ContactCSVModel.import_data(*args, **kw)

如何让[field.value]以我需要的方式工作?我已经看过像setattr()之类的东西,但我不认为这就是我所追求的。

Forms.py供参考......

COL_CHOICES = [
    ('NONE', 'No Import'),
    ('first_name', 'First Name'),
    ('last_name', 'Last Name'),
    ('company', 'Company'),
    ('mobile', 'Mobile Number'),
    ('email', 'Email Address'),
    ]


class ConfiguratorForm(forms.Form):
    col1 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')
    col2 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')
    col3 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')
    col4 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')
    col5 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name') 

2 个答案:

答案 0 :(得分:3)

class语句是type(name, bases, dict)的语法糖,因此您只需构建动态模型属性的字典并将其传递给类型,即:

def import_data(form, *args, **kw):
    class Meta:
        delimiter = ","
        dbModel = Contact
        update = {'keys': ["mobile", "group"]}
    clsmap = dict((field.value(), CharField()) for field in form)
    clsmap["Meta"] = Meta
    ContactCsvModel = type("ContactCsvModel", (CsvModel,), clsmap)         
    return ContactCSVModel.import_data(*args, **kw)

答案 1 :(得分:2)

您可以在构造对象后添加字段:

def import_data(form, *args, **kw):
    class ContactCSVModel(CsvModel):

         class Meta:
            # ...

    for field in form:
        setattr(ContactCSVModel, field.value(), CharField())

    return ContactCSVModel.import_data(*args, **kw)