1

我需要一个更好的解决方案来解决我想要在下面实现的目标。我有一个表格,这个表格需要规定以下项目 的代码顺序......

class ContactCSVModel(CsvModel):
    first_name = CharField()
    last_name = CharField()
    company = CharField()
    mobile = CharField()
    group = DjangoModelField(Group)
    contact_owner = DjangoModelField(User)

例如...

  class ContactCSVModel(CsvModel):
    if form.col1.value == "first_name":
        first_name = CharField()
    elif form.col1.value == "last_name":
        last_name = CharField()

或许

  class ContactCSVModel(CsvModel):
         [column.col1.value] = CharField()
         [column.col2.value] = CharField()

但这不会起作用,因为它会尝试分配值而不是使其成为 first_name = CharField() 等

如您所见,我最终对 col2、col3 等再次执行此操作,并最终得到了“很多”的“if 语句”。

有没有更好的方法,例如?

谢谢。

表格.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')

这是我现在未受影响的课程:

def import_data(column, *args, **kw):
    # make custom ContactCSVModel
    class ContactCSVModel(CsvModel):
        # IF column == x



        first_name = CharField()
        mobile = CharField()
        last_name = CharField()
        company = CharField()
        group = DjangoModelField(Group)
        contact_owner = DjangoModelField(User)

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

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

1 回答 1

3

之后您可以将字段添加到模型中吗,例如:

class ContactCSVModel(CsvModel):
    pass

for form_field in form:
    field_name = form_field.value
    model_field = CharField()
    model_field.contribute_to_class(ContactCSVModel, field_name)

例如(使用 Django 1.5):

from django.db import models 

class ContactCSVModel(models.Model): 
    pass 

for field_name in ('first_name', 'mobile', 'last_name'): 
    model_field = models.CharField() 
    model_field.contribute_to_class(ContactCSVModel, field_name) 

print [f.name for f in ContactCSVModel._meta.fields]

# prints:
[u'id', 'first_name', 'mobile', 'last_name']
于 2013-04-18T09:07:14.913 回答