Search code examples
pythondjangodjango-modelsmany-to-manydjango-import-export

Import ManyToMany field


I have a ManyToMany field in my models.

I want to import data and enter into that field.

My Resources.py:-

class ClinicResource(resources.ModelResource):
language = fields.Field(column_name='language',attribute='language', widget=ForeignKeyWidget(Language, 'code'))
country = fields.Field(column_name='country',attribute='country', widget=ClinicCountryForeignKeyWidget(model = Country, field ='name'))
clinic_languages = fields.Field(widget=ManyToManyWidget(ClinicLanguages, field='name'))

class Meta:
    model = Clinic
    fields = ('code', 'name', 'city', 'score')
    exclude = ('id',)
    import_id_fields = ('code', 'name', 'city', 'score', 'language', 'country')

my Models.py:-

class Clinic(models.Model):
    code = models.CharField(max_length= 10, blank= False, null= False)
    name = models.CharField(max_length= 256, blank= False, null= False)
    slug = models.SlugField(null= True, blank= True)
    # country = models.CharField(max_length= 256, blank= False, null= False)
    city = models.CharField(max_length= 256, blank= False, null= False)
    country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name='allcliniccountry', blank= True, null=True)
    score = models.FloatField(blank= False, null= False, default= 2, validators=[MinValueValidator(min), MaxValueValidator(max)])
    language = models.ForeignKey(Language, on_delete=models.CASCADE, related_name='allclinicslanguage', blank= True)
    # about = models.TextField(blank= True, null= True)
    clinic_languages = models.ManyToManyField(ClinicLanguages, related_name='clinic_language', blank= True)

    about = tinymce_models.HTMLField(blank= True, null= True)
    created= models.DateTimeField(auto_now=True)
    status = models.CharField(max_length= 30, choices= SIZE_CHOICES, default= 'pending', blank= False, null= False)

NOTE THE clinic_languages field, this is what I want to import


Solution

  • You can see how the ManyToManyWidget works in the django-import-export source.

    You have defined your field correctly:

    clinic_languages = fields.Field(widget=ManyToManyWidget(ClinicLanguages, field='name'))
    

    This means the lookup code is going to attempt to load related instances using the 'name' field. By default, they have to be separated by ',' in your import file, e.g:

    clinic_languages
    name1,name2,name3
    

    You can override the separator if necessary.