我正在使用 Django Import-Export 将数据从 excel(xlsx) 文件导入到我的 Django 模型。 我所拥有的有效,但我希望它将具有不同大小写的字符的字符串视为相同。目前,如果我在一个专栏中包含“黑色安息日”和“黑色安息日”,则导入会认为它们是不同的艺术家。
是否可以在导入过程中将所有字符串值更改为小写?或者以某种方式配置 Django 以将它们视为相同?
资源.py
class ArtistResource(resources.ModelResource):
class Meta:
model = Artist
import_id_fields = ('artist',)
skip_unchanged = True
模型.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
最佳答案
是的,文档中有描述:
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.
因此,您必须在 before_import_row()
中执行此操作,因为如果您稍后执行此操作,get_or_init_instance()
将为您创建一行。
关于python - 在导入 Django 之前将值更改为小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59012964/