【问题标题】:How do I import tags using django-import-export?如何使用 django-import-export 导入标签?
【发布时间】:2015-12-05 16:12:21
【问题描述】:

我想将某些字段导入为django-taggit 标签,使用django-import-export

我该怎么做?

【问题讨论】:

    标签: django django-taggit django-import-export


    【解决方案1】:

    您需要创建自定义导入资源和字段。此答案假定您在电子表格中有两列,标题为 '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 方法来拆分数据并将它们添加为单独的标签。

    【讨论】:

      猜你喜欢
      • 2020-04-22
      • 1970-01-01
      • 2022-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      相关资源
      最近更新 更多