如何在使用 django-import-export 导入 excel 期间避免类似的行?



我有一个 excel 文件,其中包含包含相似数据的多行。例如,员工姓名在多行中重复,但我想只将此类记录导入一次,而不是多次导入我的数据库以避免冗余。我已经看到skip_rows方法可能有助于解决这个问题,但由于文档非常有限,仍然无法弄清楚如何准确使用它。任何帮助将不胜感激:)

实现此目的的一种方法是保留已导入值的列表(基于某些标识符(,然后覆盖skip_row()以忽略任何重复项。

例如:

class _BookResource(resources.ModelResource):
imported_names = set()
def after_import_row(self, row, row_result, row_number=None, **kwargs):
self.imported_names.add(row.get("name"))
def skip_row(self, instance, original):
return instance.name in self.imported_names
class Meta:
model = Book
fields = ('id', 'name', 'author_email', 'price')

然后运行以下命令将跳过任何重复项:

# set up 2 unique rows and 1 duplicate
rows = [
('book1', 'email@example.com', '10.25'),
('book2', 'email@example.com', '10.25'),
('book1', 'email@example.com', '10.25'),
]
dataset = tablib.Dataset(*rows, headers=['name', 'author_email', 'price'])
book_resource = _BookResource()
result = book_resource.import_data(dataset)
print(result.totals)

这给出了输出:

OrderedDict([('new', 2), ('update', 0), ('delete', 0), ('skip', 1), ('error', 0), ('invalid', 0)])

我找到了一种方法来跳过数据库中已经存在的行。一种方法是将数据库中的特定字段与 excel 文件中的列进行比较。

所以在这个特定的例子中,我假设ig_username是 django 模型 InstagramData 中的一个字段,并且ig_username也存在于我想上传的 excel 文件中。 因此,在这个特定示例中ig_username如果数据库中已经存在 excel 中的值,则会跳过该值。我为这个答案受了很多苦,我不希望你 😊

class InstagramResource(resources.ModelResource):
def skip_row(self, instance, original):
check=[]
new=InstagramData.objects.all()
for p in new:
check.append(p.ig_username)
if instance.ig_username in check:
return True
else:
print("no")
return False
class Meta:
model = InstagramData
class InstagramDataAdminAdmin(ImportExportModelAdmin,admin.ModelAdmin):
resource_class = InstagramResource
admin.site.register(InstagramData,InstagramDataAdminAdmin)

最新更新