2015-09-09 2 views

Répondre

2

Vous devrez créer une ressource et un champ d'importation personnalisés. Cette réponse suppose que vous avez deux colonnes dans la feuille de calcul, intitulées 'Tag one' et '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 

Si vous importez plusieurs balises à partir d'une seule colonne, vous pourriez adapter la méthode TagField.save de partager les données et les ajouter en tant que balises individuelles.