如何使用django-import-export为批量文件导入中使用的外键编写导入代码?

时间:2019-09-18 07:14:56

标签: django django-import-export

“我正在尝试将数据导入到我的一个模型中,但是由于模型具有foreignKey ID而失败。”

我面临同样的问题,但给出的解决方案无法正常工作。 Adding foreignKey widget to django-import-export

在django-import-export中没有有关“导入”的更多解释。

models.py

from django.db import models
from import_export import resources


class City(models.Model):
    name = models.CharField(max_length=100)
    slug = models.CharField(max_length=100)
    id = models.IntegerField(unique=True)

class Zone(models.Model):
    city = models.ForeignKey(City, to_field='id')
    name = models.CharField(max_length = 100)



我的管理员。py

from import_export.admin import ImportExportModelAdmin

#Class for django-import-export
class ZoneResource(resources.ModelResource):
    # city_id = fields.Field()
    city_id = fields.Field(
        column_name='city_id',
        attribute='city_id',
        widget=ForeignKeyWidget(City))

    class Meta:
        model = Zone
        fields = ('id', 'city_id', 'cash_limit_applicable', 'LFCL', 'UFCL',)
        import_id_fields = ('id',)
        import_order = ('id', 'city_id', 'cash_limit_applicable', 'LFCL', 'UFCL',)
        export_order = ('id', 'city_id', 'cash_limit_applicable', 'LFCL', 'UFCL',)
        skip_unchanged = True
        report_skipped = True


    def get_instance(self, instance_loader, row):
        # Returning False prevents us from looking in the
        # database for rows that already exist
        print "get instance"
        return False

    def dehydrate_city_id(self, zone):
        print zone, ', hellocity'
        if zone is not None:
            return zone.city.id  # You can get all fields of related model.
        else:
            return zone

class ZoneAdmin(AdminPermissionMixin, ImportExportModelAdmin):
    resource_class = ZoneResource
    fields = ['name', 'LFCL', 'UFCL', 'cash_limit_applicable']
    list_display = (
        'id', 'name', 'city', 'LFCL', 'UFCL', 'floating_cash_submit_limit', 'allowable_cash_limit',
        'enabled', 'cash_limit_applicable', 'floating_cash_limit')

    def get_import_form(self):
        return CustomImportForm

    def get_confirm_import_form(self):
        return CustomConfirmImportForm

    def get_form_kwargs(self, form, *args, **kwargs):
        # update kwargs with authors (from CustomImportForm.cleaned_data)
        if isinstance(form, CustomImportForm):
            if form.is_valid():
                print "city form"
                city = form.cleaned_data['city']
                kwargs.update({'city': city.id})
        return kwargs

admin.site.register(Sol, SolAdmin)

form.py

class CityFormMixin(forms.Form):
    city = forms.ModelChoiceField(queryset=City.objects.all(),
                                    required=True)


class CustomImportForm(CityFormMixin, ImportForm):
    """Customized ImportForm, with author field required"""
    pass


class CustomConfirmImportForm(CityFormMixin, ConfirmImportForm):
    """Customized ConfirmImportForm, with author field required"""
    pass

错误

"%s has no %s." % (self.field.model.__name__, self.field.name)
RelatedObjectDoesNotExist: Zone has no city.

谢谢您的帮助。

0 个答案:

没有答案