2

django-import-exportを使用して、特定のフィールドをdjango-taggitタグとしてインポートしたいと考えています。

どうすればいいですか?

4

1 に答える 1

2

カスタム インポート リソースとフィールドを作成する必要があります。この回答は、スプレッドシートに と というタイトルの 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

1 つの列から複数のタグをインポートする場合はTagField.save、データを分割して個別のタグとして追加するようにメソッドを適応させることができます。

于 2015-09-09T15:37:58.340 に答える