Search code examples
pythondjangodjango-import-export

django-import-export KeyError: u'CUSTOM_PRIMARY_KEY'


class ProductResource(resources.ModelResource):
    class Meta:
        model = Product
        exclude = ('pub_date','modified_date',)
        import_id_fields = ('CD-SKU',)

class ProductAdmin(ImportExportModelAdmin):
        resource_class = ProductResource

The error is:

Line number: 1 - u'CD-SKU'
0H041501, VOL3380235300029, 3380235300029, B00FIZJI0K, 11.59, None, None, None, None, None, None, None, None, None
Traceback (most recent call last):
File "/home/mws/Env/mws_prod/local/lib/python2.7/site-packages/import_export/resources.py", line 434, in import_row
instance, new = self.get_or_init_instance(instance_loader, row)
File "/home/mws/Env/mws_prod/local/lib/python2.7/site-packages/import_export/resources.py", line 258, in get_or_init_instance
instance = self.get_instance(instance_loader, row)
File "/home/mws/Env/mws_prod/local/lib/python2.7/site-packages/import_export/resources.py", line 252, in get_instance
return instance_loader.get_instance(row)
File "/home/mws/Env/mws_prod/local/lib/python2.7/site-packages/import_export/instance_loaders.py", line 31, in get_instance
field = self.resource.fields[key]
KeyError: u'CD-SKU'

After reading related questions, I removed the native auto generated id and used my own field as the primary. Mentioned it in the Resource class. But still its not able to import.

Would appreciate all the help. Thanks!


Solution

  • Looks like you just have a typo. What your model has is CD_SKU and you resource uses CD-SKU:

    class Product(models.Model):
        CD_SKU = models.CharField(max_length = 200, primary_key=True) 
    

    vs

    import_id_fields = ('CD-SKU',)
    

    Change it to:

    import_id_fields = ('CD_SKU',)
    

    Hope it helps!