I'm using Django-import-export module in my admin panel. I import .csv file extracted from our ERM system which updates records in Django myapp database. Everything works like a charm, except that when some records are removed from ERM and are not present in .csv datadump, no updates will be done in the Django database since records do not exist.
I want to write a clause when importing .csv file, change or delete (preferably change record name to "deleted") all records not present in mentioned .csv file. Records are identified by "number" column which is a primary key in the database.
Closest solution I could find was to add "delete" column and set "1" in uploaded file, however that does not help since those records don't exist in the first place.
Here's how my admin.py looks like:
from django.contrib import admin
from .models import Supplier, SiteServices
from import_export import resources, widgets, fields
from import_export.admin import ImportExportModelAdmin
# Register your models here.
class SupplierResource(resources.ModelResource):
delete = fields.Field(widget=widgets.BooleanWidget())
def for_delete(self, row, instance):
return self.fields['delete'].clean(row)
class Meta:
model = Supplier
import_id_fields = ['number']
class SupplierAdmin(ImportExportModelAdmin, admin.ModelAdmin):
resource_class = SupplierResource
admin.site.register(Supplier, SupplierAdmin)
Override after_import_instance
and save all imported ids in some variable, lets call it imported_ids
. Override after_import
and update Suppliers that are not in imported_ids
.
See all hooks in documentation:
https://django-import-export.readthedocs.io/en/latest/api_resources.html#import_export.resources.Resource.after_import_row
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With