1

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
4
  • 1
    Please show every solution you've tried. The reason would be that it would be a waste of time for others to post suggestions that you've already tried. Also, you are importing a CSV. What does the CSV look like? Is there a mismatch of expected fields and actual fields? Commented Nov 28, 2023 at 3:46
  • Thanks! The question has been changed upon your advice. Commented Nov 28, 2023 at 6:37
  • In your CSV file, there are blank values for "license" column. So your HCPMaster class should have license field with null=True and blank=True Commented Nov 28, 2023 at 6:41
  • It should work due to import_id_fields being present in Resource and in file (docs). Best to step through with debugger and figure out what's going wrong. Also use resource_classes not resource_class. Please post back if you find the problem. Commented Nov 28, 2023 at 9:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.