在django-import-export中导入m2m关系 [英] import m2m relation in django-import-export

查看:75
本文介绍了在django-import-export中导入m2m关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用应用程序django-import-export。这是其中一个模型的示例配置:

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']

网站和类别-是一个m2m字段。
导出工作正常,我们得到了以下内容的CSV文件:

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"

但是当您尝试导入m2m字段时未添加。如何使用m2m关系导入数据?!

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

推荐答案

django-import-export 有自己的小部件处理模型关系:

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']

在此处检查其他小部件: django导入导出小部件

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

这篇关于在django-import-export中导入m2m关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆