2

I want to import certain fields as django-taggit tags, using django-import-export.

How do I do this?

4

1 回答 1

2

You will need to create a custom import resource and field. This answer assumes that you have two columns in the spreadsheet, entitled 'Tag one' and '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

If you are importing multiple tags from a single column, you could adapt the TagField.save method to split the data and add them as individual tags.

于 2015-09-09T15:37:58.340 回答