0

仍然在尝试传递列对象时遇到问题,因此我可以在 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)
4

1 回答 1

1

您可以即时上课:

def foo(column):
    class Foo(object):
        if column == 'a':
            bar = 'a'
            foo = 'c'
        else:
            bar = 'b'

    return Foo

for x in 'ab':
    cls = foo(x)
    print cls.bar
    print cls.foo

还有其他方法可以做到这一点,查找有关元类的信息。是关于这个主题的一个非常好的讲座。

在你的情况下,我会这样做:

def import_data(column, *args, **kw):
    # make custom ContactCSVModel
    class ContactCSVModel(CsvModel):
        # 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"]}

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

# in another file, you can even mask it as your model class,
# I wouldn't do that however
import somemodule as ContactCSVModel

# Try and import CSV
ContactCSVModel.import_data(form, data=file, extra_fields=[
                           {'value': upload.group_id, 'position': 5},
                           {'value': upload.uploaded_by.id, 'position': 6}])


# or you could make a function that returns a class
def contact_model(column):
    # make class
    return ContactModel

# then
from somemodule import contact_model

ContactCSVModel = contact_model(column=form)

# then use as normally
ContactCSVModel.import_data(data=file, extra_fields=[
                           {'value': upload.group_id, 'position': 5},
                           {'value': upload.uploaded_by.id, 'position': 6}])
于 2013-04-17T21:30:45.110 回答