仍然在尝试传递列对象时遇到问题,因此我可以在 ContactCSVModel 中使用它。
我怎样才能做到这一点?
这就是我使用它的方式...
# Try and import CSV
ContactCSVModel.import_data(data=file, extra_fields=[
{'value': upload.group_id, 'position': 5},
{'value': upload.uploaded_by.id, 'position': 6}], column=form)
这是课...
class ContactCSVModel(CsvModel):
I WANT TO USE 'column' HERE
I.E.
IF column == x
first_name = CharField()
last_name = CharField()
company = CharField()
mobile = CharField()
group = DjangoModelField(Group)
contact_owner = DjangoModelField(User)
class Meta:
delimiter = ","
dbModel = Contact
update = {'keys': ["mobile", "group"]}
CSV模型
class CsvModel(BaseModel):
def __init__(self, data, delimiter=None):
super(CsvModel, self).__init__(data)
self.delimiter = None
if delimiter:
self.delimiter = delimiter
elif self.has_class_delimiter():
self. delimiter = self.cls.Meta.delimiter
if not isinstance(data, Model):
self.construct_obj_from_data(data)
else:
self.construct_obj_from_model(data)
def validate(self):
if len(self.attrs) == 0:
raise ImproperlyConfigured("No field defined. Should have at least one field in the model.")
if not self.cls.has_class_delimiter() and not getattr(self, "delimiter", False) and len(self.attrs) > 1:
raise ImproperlyConfigured(
"More than a single field and no delimiter defined. You should define a delimiter.")
@classmethod
def get_importer(cls, extra_fields=[]):
return CsvImporter(csvModel=cls, extra_fields=extra_fields)
def construct_obj_from_data(self, data):
self.validate()
values = {}
silent_failure = self.cls.silent_failure()
self.multiple_creation_field = None
composed_fields = []
index_offset = 0
data_offset = 0
for position, (attr_name, field) in enumerate(self.attrs):
field.position = position
if isinstance(field, ComposedKeyField):
composed_fields.append(field)
index_offset += 1
continue
if self.cls.has_class_delimiter() or self.delimiter:
value = data.pop(position - index_offset - data_offset)
data_offset += 1
else:
value = data.pop(0)
try:
if isinstance(field, IgnoredField):
continue
if hasattr(field, 'has_multiple') and field.has_multiple:
remaining_data = [value] + data[:] # value should be re-added
# as it has been pop before
multiple_values = []
for data in remaining_data:
multiple_values.append(self.get_value(attr_name, field, data))
self.set_values(values, self.field_matching_name, multiple_values)
self.multiple_creation_field = self.field_matching_name
else:
value = self.get_value(attr_name, field, value)
self.set_values(values, self.field_matching_name, value)
except ValueError, e:
if silent_failure:
raise SkipRow()
else:
raise e
if self.cls.is_db_model():
for field in composed_fields:
keys = {}
for key in field.keys:
keys[key] = values.pop(key)
values[self.field_matching_name] = self.get_value(attr_name, field, keys)
self.create_model_instance(values)