Adding a foreignKey widget to django-import-export

I am trying to import data into one of my models, but it fails because I am trying to load the foreignKey identifier, and not the iterated number that the import-export creates.

models.py

from django.db import models from import_export import resources class School(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=100) school_id = models.IntegerField(unique=True) class Sol(models.Model): school_id = models.ForeignKey(School, to_field='school_id') name = models.CharField(max_length = 100) Al1EOC = models.DecimalField(max_digits=5, decimal_places=2) AL2EOC = models.DecimalField(max_digits=5, decimal_places=2) #Class for django-import-export class SolResource(resources.ModelResource): class Meta: model = Sol 

My admin.py

 from import_export.admin import ImportExportModelAdmin class SolAdmin(ImportExportModelAdmin): list_display = ('name', 'school_id') resources_class = SolResource pass admin.site.register(Sol, SolAdmin) 

My .csv details

 id, name, school_id, Al1EOC, AL2EOC ,'Main st school', 1238008, 12.9, 14.9 

When I export data from the SOL model, I get an iterated number for the school identifier. I want the actual school identifier to be the one that contains the foreignKey relationship. And, subsequently, I need to load data with this foreignKey number. I know that a ForeignKey widget is a way to do this, but I don’t understand how it is implemented.

+6
source share
3 answers

I think this will help:

 class SolResource(resources.ModelResource): school_id = fields.Field() class Meta: # ... def dehydrate_school_id(self, sol): return sol.school_id.school_id # You can get all fields of related model. This is example. 
+3
source

Use widgets perfectly.

school_id = fields.Field(column_name='school_id', attribute='Sol', widget=widgets.ForeignKeyWidget(Sol, 'school_id'))

+3
source

The documentation has a ForeignKeyWidget . You can use it here. There are also IntegerWidget and DecimalWidget.

 from import_export.admin import ImportExportModelAdmin class SolResource(resources.ModelResource): school_id = fields.Field( column_name='school_id', attribute='school_id', widget=ForeignKeyWidget(School, 'name')) class Meta: model = Sol class SolAdmin(ImportExportModelAdmin): list_display = ('name', 'school_id') resources_class = SolResource admin.site.register(Sol, SolAdmin) 

This is a working example. Hope this helps.

+3
source

Source: https://habr.com/ru/post/974839/


All Articles