2013-04-17 177 views
0

嘗試傳遞列對象時仍存在問題,因此我可以在ContactCSVModel中使用它。Django將對象傳遞給類

我該怎麼做?

這是我如何使用它...

# 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"]} 

CsvModel

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) 

回答

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 

還有其他方法可以做到這一點,查閱元類的信息。 Here是一個非常好的講座。

在你的情況我會怎麼做:

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}]) 
+0

但請問是給定的工作,多數民衆贊成我打電話ContactCSVModel.import_data – Prometheus

+0

也是我不使用Python 3中,雖然我將觀看該視頻。 – Prometheus

+0

這不僅僅是Python 3,對於2.x也是有趣的東西。我用'import_data'的例子更新了代碼。 – gatto