user12279006
user12279006

Reputation:

Change values to lowercase before importing to Django

I am using Django Import-Export to import data from an excel(xlsx) file to my Django Models. What I have works but I want it to consider strings with characters that have different cases to be the same. Currently if I have 'Black Sabbath' and 'black sabbath' in a column, the import considers them to be different artists.

Is it possible to change all string values to lowercase during the import process? Or somehow configure Django to consider them the same?

resources.py

class ArtistResource(resources.ModelResource):

    class Meta:
        model = Artist
        import_id_fields = ('artist',)
        skip_unchanged = True

models.py

class Artist(models.Model):
    artist = models.CharField(primary_key=True, unique=True, max_length=30)

    def __str__(self):
        return self.artist

admin.py

class ArtistAdmin(ImportExportActionModelAdmin):
    resource_class = ArtistResource

Upvotes: 1

Views: 600

Answers (2)

user12279006
user12279006

Reputation:

For any future readers who might want my solution.

class ArtistResource(resources.ModelResource):

    class Meta:
        model = Artist
        import_id_fields = ('artist',)
        skip_unchanged = True

    def before_import_row(self, row, **kwargs):
        row['artist'] = row['artist'].lower()

Upvotes: 2

user1600649
user1600649

Reputation:

Yes and it is described in the documentation:

Each row of the to-be-imported dataset is processed according to the following steps:

  1. The before_import_row() hook is called to allow for row data to be modified before it is imported
  2. get_or_init_instance() is called with current BaseInstanceLoader and current row of the dataset, returning an object and a Boolean declaring if the object is newly created or not.

So you must do this in before_import_row(), because if you do it any later get_or_init_instance() will have created a the row for you.

Upvotes: 2

Related Questions