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?!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With