Search code examples
pythonpython-3.xdjangocsvexport-to-csv

Import data from a CSV file without id as column


I would like to know if it's possible to import data but with a table that does not have a column named id

My import are doing fine with every table that contained a column id but with the one that does not contained a column id it does not work. I got a row_error saying : Error: 'id'

Model that can't be imported

class CustomizingObject(models.Model):
    code = models.CharField(max_length=40, primary_key=True, unique=True, help_text="Human readable code")

My function

from import_export import resources

lo_resource = resources.modelresource_factory(model=lo_resource_to_import)() # lo_resource_to_import is the model
with open(lv_local_filename, 'r', encoding='utf-8') as f:
    csv_data = f.read()
    lt_dataset = tablib.Dataset().load(csv_data, 'csv')

result = lo_resource.import_data(lt_dataset, dry_run=True)
if not result.has_errors():
    result = lo_resource.import_data(lt_dataset, dry_run=False)
    Logger.Info("import", 2) # Import over
else :
    Logger.Error("import", 3, lv_local_filename) # Input file {} has error
    for ld_error in result.row_errors():
        Logger.Error("import", 5, ld_error[1][0].error) # Error: {}

Solution

  • Django provide a import_id_fields so we can specify fields that we wants to import. Without it, it always look for a field ID.

    The solution was to emcapsulate my class with resources.ModelResource and specify import_id_fields.

    class CustomizingObjectResource(resources.ModelResource):
    
        class Meta:
            model = CustomizingObject
            import_id_fields = ('code',)
            fields = ('code')
    

    My function

    # specific is a parameter of my function here specific = CustomizingObjectResource
    if specific is not None:
        lo_resource = specific()
    else:
        lo_resource = resources.modelresource_factory(model=lo_resource_to_import)()
    with open(lv_local_filename, 'r', encoding='utf-8') as f:
        csv_data = f.read()
        lt_dataset = tablib.Dataset().load(csv_data, 'csv')
    
    result = lo_resource.import_data(lt_dataset, dry_run=True)
    if not result.has_errors():
        result = lo_resource.import_data(lt_dataset, dry_run=False)
        Logger.Info("import", 2) # Import over
    else :
        Logger.Error("import", 3, lv_local_filename) # Input file {} has error
        for ld_error in result.row_errors():
            Logger.Error("import", 5, ld_error[1][0].error) # Error: {}