Getting KeyError: 'id' when importing a CSV file using django-import-export

70 Views Asked by At

I am tring to update sqlite data by importing a csv file to django admin, only to get the error message for each single record I upload:

Line number: 1 - 'id'
Traceback (most recent call last):
...
import_id_fields = [self.fields[f] for f in self.get_import_id_fields()]
KeyError: 'id'

Here is my models.py, which indicates a primary key:

class HCPMaster(models.Model):
    external_id = models.CharField(max_length=200, primary_key=True)
    bi_external_id = models.CharField(max_length=200)
    name = models.CharField(max_length=200)
    ...

The resources.py, which has the import_id_fields:

class HCPMasterResource(resources.ModelResource):
    class Meta:
        model = HCPMaster
        import_id_fields = ['external_id']

The admin.py:

class HCPMasterAdmin(ImportExportModelAdmin):
    resources_class = HCPMasterResource
    
admin.site.register(HCPMaster, HCPMasterAdmin)

The uploaded csv file (The columns match the HCPMaster model exactly):

external_id,bi_external_id,name,primary_parent_name,parent_external_id,parent_parent_external_id,personal_title,administrative_title,license,network_external_id,status,verified_time,updated_time
CNC1562173,CN1183335,John,Hospital A,Hospital A,CNHABCD,Doctor,Agent,,9.36678E+17,Active,44851,45231
CNC1531568,CN1183339,Mary,Hospital B,Hospital B,CNHABCE,Doctor,Agent,,9.37537E+17,Active,44799,45231

I have tried every possible solution on stackoverflow and github like:

  1. Specify import_id_fields to the actual primary key 'external_id'.
  2. Specify exclude = ['id'] in Meta Class of ModelResource.
  3. Specify fields in Meta Class of ModelResource: List all the fields in CSV file.
  4. Manually Create a id columns in the csv file with blank value. Sadly, none of them works.

pip list:

Django                 4.2.7
django-import-export   3.3.3
0

There are 0 best solutions below