Reputation:
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
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
Reputation:
Yes and it is described in the documentation:
Each row of the to-be-imported dataset is processed according to the following steps:
- The before_import_row() hook is called to allow for row data to be modified before it is imported
- 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