Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import m2m relation in django-import-export

Tags:

python

django

use application django-import-export. Here is an example configuration for one of the models:

class ImportExportAdsTypeResource(resources.ModelResource):
    class Meta:
        model = AdType
        import_id_fields = ('name',)
        fields = ['name', 'active', 'position', 'categories', 'sites']

sites and categories - is a m2m field. Export works fine, we get such CSV file with the following contents:

name,active,position,sites,categories
Excport CSV test,1,13,1,"19,26"

but when you try to import m2m field are not added. How to import data with m2m relationships?!

like image 900
Алексей Стародубцев Avatar asked Dec 03 '15 11:12

Алексей Стародубцев


1 Answers

django-import-export has it's own widgets to handle models relationships:

    from import_export import fields, resources
    from import_export.widgets import ManyToManyWidget

    class ImportExportAdsTypeResource(resources.ModelResource):
        categories = fields.Field(widget=ManyToManyWidget(Category))
        sites = fields.Field(widget=ManyToManyWidget(Site))

        class Meta:
            model = AdType
            import_id_fields = ('name',)
            fields = ['name', 'active', 'position', 'categories', 'sites']

Check here for other widgets: django-import-export Widgets

like image 86
Dhia Avatar answered Nov 20 '22 04:11

Dhia