Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-import-export change/remove records absent in uploaded file against db

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)
like image 907
Trm Avatar asked Oct 19 '25 20:10

Trm


1 Answers

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

like image 158
bmihelac Avatar answered Oct 22 '25 10:10

bmihelac