Search code examples
djangodjango-import-export

How i can to delete record when import file using django-import-export?


My project use Django framework and installed django-import-export plugin. I can import and export everything normally. But when i imported file to database. All new records from file upload was imported successfully. but old record that is not in the new records not delete.

old data in database

ID , Name , wage
1 , Mr.A , 100
2 , Mr.B , 110
3 , Mr.C , 150 

new file upload

ID , Name , wage
1 , Mr.A , 100
2 , Mr.B , 150
4 , Mr.D , 130  

the result when imported

ID , Name , wage
1 , Mr.A , 100
2 , Mr.B , 150
3 , Mr.C , 150  # < this not delete
4 , Mr.D , 130  

I want it to be like this in database.

----------
ID , Name , wage
1 , Mr.A , 100
2 , Mr.B , 150
4 , Mr.D , 130  

How i can to delete old record when imported using django-import-export plugins?

here my code

class PersonalResource(resources.ModelResource):
    class Meta:
        model = Personal
        import_id_fields = ('p_id',)
        

class PersonalAdmin(ImportExportModelAdmin,admin.ModelAdmin):
    resource_class = PersonalResource
    list_display = ['p_id','name','poistion','dept']
    search_fields = ['p_id']

    

Solution

  • django-import-export won't do this for you by default, but you can easily add some hooks to achieve this.

    You can track the id of each row imported or updated, and then delete any others at the end of the import.

    for example:

    class PersonalResource(resources.ModelResource):
        instances_to_keep = set()
    
        def after_save_instance(self, instance, using_transactions, dry_run):
            self.instances_to_keep.add(instance.id)
    
        def after_import(self, dataset, result, using_transactions, dry_run, **kwargs):
            Personal.objects.exclude(id__in=self.instances_to_keep).delete()
    
        class Meta:
            model = Personal
            import_id_fields = ('p_id',)
    

    Some points to note:

    • Read up on the implications of delete()
    • You might consider running this in a transaction for smaller datasets.