Adding foreignKey widget to django-import-export

后端 未结 3 1875
野的像风
野的像风 2020-12-31 14:30

I\'m trying to import data to one of my models, but it\'s failing because I\'m trying to upload the foreignKey Id, not the iterated number that import-export creates.

<
相关标签:
3条回答
  • 2020-12-31 14:46

    There is ForeignKeyWidget in the documentation. 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 it will help.

    0 讨论(0)
  • 2020-12-31 14:49

    Use the widget- works great.

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

    0 讨论(0)
  • 2020-12-31 14:57

    i think it 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.
    
    0 讨论(0)
提交回复
热议问题