我想使用django-taggit将某些字段导入为django-import-export个标记。
我该怎么做?
答案 0 :(得分:2)
您需要创建自定义导入资源和字段。此答案假设您在电子表格中有两列,分别为'Tag one'
和'Tag two'
。
from import_export import resources, fields, widgets
from django.utils.encoding import force_text
from .models import MyModel
class TagField(fields.Field):
"An import resource field for importing tags."
def __init__(self, attribute='tags', column_name=None, widget=None,
readonly=False):
# Use 'tags' column name by default
super(TagField, self).__init__(
attribute, column_name, widget, readonly)
def export(self, obj):
# Because of the way import_export works,
# it's difficult to get this value
return '[preview not supported]'
def clean(self, data):
# The standard M2M widget tries to return a pk of the model. In
# the case of tags, we just want to return the text, and then we'll
# create it when we save.
try:
return force_text(data[self.column_name])
except KeyError:
raise KeyError("Column '%s' not found in dataset. Available "
"columns are: %s" % (self.column_name, list(data.keys())))
def save(self, obj, data):
# Save the tag
value = self.clean(data)
obj.tags.add(value)
class MyModelResource(resources.ModelResource):
tag_one = TagField(column_name='Tag One',
widget=widgets.ManyToManyWidget(ResearchItem))
tag_two = TagField(column_name='Tag Two',
widget=widgets.ManyToManyWidget(ResearchItem))
class Meta:
model = MyModel
fields = ('tag_one', 'tag_two')
export_order = fields
如果要从单个列导入多个标记,则可以调整TagField.save
方法以拆分数据并将其添加为单个标记。