django导入导出如何添加外键

gzszwxb4  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(203)

我正在使用django-import-export将excel导入到我的模型中,我所做的是创建一个表单,其中包含一些输入,从那里加载文件,然后在form_valid()中处理文件以将其加载到数据库中,模型有两个外键“id_order”和“gestion”;“id_orden”来自excel,“gestion”我使用gestion= Gestion.objects.get(idgestion=obj.pk)获取它,这是我要保存的表单的ID,但我想知道的是如何将“gestion”传递给ModelResource,然后将其保存到数据库

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', )
x33g5p2x

x33g5p2x1#

这很容易做到。您需要将gestion值传递到您的Resource中,然后在持久化之前将其链接到示例:

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)

显然,这意味着从数据集中的行创建的所有示例都将链接到同一个“gestion”值。
btw import-export集成了django-admin,所以你可以使用admin界面导入数据,而不用自己写表单(如果你需要的话).更多信息请看文档.

相关问题