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