django-import-export: cannot exclude id field during import : KeyError: u'id'

后端 未结 3 1745
无人共我
无人共我 2020-12-18 17:15

On Django-1.9.6, django-import-export-0.5

When I try to upload CSV without \"id\" field throws this error.

Line number: 1 - u\'id\'
13173474, Harry          


        
3条回答
  •  旧巷少年郎
    2020-12-18 17:54

    i have figure out the solution to import without ID column Here is code , Take a Look

        if request.method == 'POST':
        queryset = Client.objects.filter(company=company)
        company = Company.objects.get(id=company)
        person_resource = ClientResource()
        dataset = Dataset()
        new_persons = request.FILES['myfile']
        imported_data = dataset.load(new_persons.read().decode('utf-8'), format='csv')
        try:
            for row in dataset:
                client = Client()
                client.company = company
                client.title = row[0]
                client.first_name = row[1]
                client.last_name = row[2]
                client.email = row[3]
                client.position = row[4]
                client.company_name = row[5]
                client.vat_number = row[6]
                client.website = row[7]
                client.address = row[8]
                client.city = row[9]
                client.state = row[10]
                client.zip = row[11]
                client.country = row[12]
                client.phone = row[13]
                client.fax = row[14]
                client.notes = row[15]
                client.save()
    
        except Client.DoesNotExist:
            raise Http404("There is a Problem with The CSV")
    
    return render(request, 'import.html')
    

    And my Resource Looks Like this

    class ClientResource(resources.ModelResource):
    company = fields.Field(
        column_name='company',
        attribute='company',
        widget=ForeignKeyWidget(Company, 'name'))
    
    class Meta:
        model = Client
        skip_unchanged = True
        report_skipped = True
        exclude = ('id', 'company', 'status', 'modified', 'created')
        import_id_fields = ['email']
    

提交回复
热议问题