Reputation: 113
When trying to import data via excel, the code only reads first entry from data-base.
#resource.py
from .models import(
Country, GeoMaster
)
from import_export import resources, fields
from import_export.widgets import ForeignKeyWidget
class CountryResource(resources.ModelResource):
geo_master_id= fields.Field(
column_name= 'geo_master_id',
attribute='geo_master_id',
widget=ForeignKeyWidget(GeoMaster, 'id')
)
class Meta:
model = Country
import_id_fields = ['country_name']
fields = ( 'id', 'country_name', 'geo_master_id')
My model GeoMaster
contains multiple entries with id's ranging from 1-10
my successful import dataset (geo_master_id=1 is first entry in databse):
id|country_name|geo_master_id
--|--------------|--------------|
|India |1.0 |
un-successful import dataset (geo_master_id=2 is NOT first entry in databse):
id|country_name|geo_master_id
--|--------------|--------------|
|India |2.0 |
Error: GeoMaster matching query does not exist. Is there somethinf wrong with my #resources.py?
UPDATE: I added custom widget:
class GeoMasterForeignKeyWidget(ForeignKeyWidget):
def get_queryset(self, value, row):
return self.model.objects.filter(
id=row["geo_master_id"],
)
#to be used in subsequent field
geo_master_id= fields.Field(
column_name= 'geo_master_id',
attribute='geo_master_id',
widget=GeoMasterForeignKeyWidget(GeoMaster, 'id')
)```
Still it returns Error: GeoMaster matching query does not exist.
Upvotes: 0
Views: 242
Reputation: 113
I tried this and it worked for me
class GeoMasterForeignKeyWidget(ForeignKeyWidget):
def get_queryset(self, value, row):
#print(int(value), row)
qs= GeoMaster.objects.filter(
id=int(value),
)
print("returning:", qs)
return qs
Upvotes: 1