Home > Software design >  django import-export how to add foreign key
django import-export how to add foreign key

Time:12-11

I am using django-import-export to import an excel to my model, what I do is that I create a form with some inputs from where it loads the file, then in form_valid() I process the file to load it to the database, the model has two foreign keys 'id_order' and 'gestion'; 'id_orden' comes in the excel and 'gestion' I get it with gestion= Gestion.objects.get(idgestion=obj.pk) which is the id of the form that I am saving, but what I want to know is how I can pass 'gestion' to ModelResource and then save it to the database

view.py
class GestionView(CreateView):
    model = Gestion
    form_class = GestionForm
    template_name = 'asignacion/gestion.html'
    success_url = reverse_lazy('asignacion_url:gestion')

    def form_valid(self, form):
        isvalid = super().form_valid(form)
        obj = form.save()
        gestion= Gestion.objects.get(idgestion=obj.pk)
        file = self.request.FILES['file']
        item_gestion =ItemResourceResource()
        dataset = Dataset()
        imported_data = dataset.load(file.read(), format='xls')
        result = item_gestion.import_data(dataset, dry_run=True)
        if not result.has_errors():
            item_gestion.import_data(dataset, dry_run=False)

model.py
class ItemGestion(models.Model):
    idgestion = models.AutoField(primary_key=True)
    numero_imagenes = models.CharField(max_length=45, blank=True, null=True)
    id_orden = models.ForeignKey('Asignacion', models.DO_NOTHING)
    aviso_sap = models.CharField(max_length=45, blank=True, null=True)
    poliza = models.CharField(max_length=45, blank=True, null=True)
    observacion_cierre = models.CharField(max_length=250, blank=True, null=True)
    gestion=models.ForeignKey('Gestion', models.DO_NOTHING)

resources.py
class ItemResourceResource(resources.ModelResource):
    id_orden = fields.Field(column_name='id_orden', attribute='id_orden',
                                widget=ForeignKeyWidget(Asignacion,'id_orden'))
    
    class Meta:
        model = ItemGestion
        import_id_fields = ('id_orden',)
        exclude = ('idgestion', )

CodePudding user response:

It is easy to do. You need to pass the gestion value into your Resource, and then link it to the instance before it is persisted:

class ItemResourceResource(ModelResource):

    def __init__(self, gestion):
        self.gestion = gestion

    def before_save_instance(self, instance, using_transactions, dry_run):
        instance.gestion = self.gestion

    class Meta:
        # ...
gestion = Gestion.objects.get(idgestion=obj.pk)
item_gestion = ItemResourceResource(gestion)

Obviously this means that all the instances created from the rows in your dataset will be linked to the same 'gestion' value.

btw import-export integrates with django-admin, so you can use the admin interface to import data rather than writing your own forms (if that fits your requirements). See the docs for more information.

  • Related