0

我需要在运行时根据 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') 
4

2 回答 2

4

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)
于 2013-04-18T11:23:48.317 回答
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)
于 2013-04-18T11:35:10.020 回答