[Django]-Django-import-export error while importing data into database

4๐Ÿ‘

I had a similar problem.
It is that for import django import-export uses โ€œidโ€ by default.
First, create a resources.py file โ€“ where you will declare settings for import and export. And as an exception, declare โ€œidโ€.

resources.py

from import_export import resources
from .models import *

class PropertyAdminResource(resources.ModelResource):

    class Meta:
        model   =   PropertyModel
        exclude = ('id',)

admin.py

from .resources import *

@admin.register(PropertyModel)
class PropertyAdmin(ImportExportModelAdmin):
    resource_class  =   PropertyAdminResource
    list_display = ['Property_ID', 'Created_By', 'Last_Updated_By']

I highly recommend using resources.py โ€“ where you can modify the methods for import and export.

๐Ÿ‘คDavid Grigoryev

1๐Ÿ‘

you need to let the resources model know your primary key, if it didnโ€™t find it will automatically set it to โ€˜idโ€™

here is an example

models.py

class Product(models.Model):
  my_id =  models.CharField(max_length=255, primary_key=True)

admin.py

from import_export.admin import ImportExportModelAdmin
from import_export import resources

class ProductAdminResource(resources.ModelResource):
    class Meta:
         model = Product
         import_id_fields = ['my_id']

@admin.register(Product)
class ProductAdminView(ImportExportModelAdmin):
    resource_class = ProductAdminResource
๐Ÿ‘คMamoun Kubur

0๐Ÿ‘

I had some errors like you and managed to solve them following this answer โ€“ https://github.com/django-import-export/django-import-export/issues/92#issuecomment-598009569

I changed from version 2.0.2 to 2.0.1, removed the custom primary key and migrated again

I hope this helps with your problem

๐Ÿ‘คrahman Muhamamd

0๐Ÿ‘

Please read
https://django-import-export.readthedocs.io/en/latest/getting_started.html#customize-resource-options

So for your your model you could do

class PropertyAdminResource(resources.ModelResource):
            

    class Meta:
        model = PropertyModel
        
        import_id_fields = ('Property_ID',)
        
class PropertyModelAdmin(ImportExportModelAdmin):
    resource_class = PropertyAdminResource
        
        
admin.site.register(PropertyModel, PropertyModelAdmin)

tested with django-import-export 2.7.0

๐Ÿ‘คNwawel A Iroume

Leave a comment