Search code examples
djangodjango-modelsdjango-admindjango-import-exportdjango-admin-tools

Import M2M Empty values imported


Using Widget Many to many when importing the result is empty. Tags do exists in the original model.

See Image.

import result

Excel imported

| provider  | tag             | provider_tag_id |
|-----------|-----------------|-----------------|
| Lionsgate | Planes, Top     |                 |
| FOX       | Houses, Low     |                 |
| Dorcel    | something, else |                 |

Model where the m2m is pointing

class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=250, unique=True)

    def __str__(self):
        return self.name

Model where the m2m relationship is

class ProviderTag(models.Model):
    provider_tag_id = models.AutoField(primary_key=True)
    provider = models.ForeignKey(Provider, on_delete=models.DO_NOTHING)
    tags = models.ManyToManyField(Tag)

Resource to import

class ProviderTagResource(resources.ModelResource):

provider = fields.Field(
    column_name='provider',
    attribute='provider',
    widget=ForeignKeyWidget(Provider, 'name')
)
tags = fields.Field(
    column_name='tags',
    attribute='tags',
    widget=ManyToManyWidget(Tag, separator=',', field='name')
)

class Meta():
    model = ProviderTag
    fields = ('provider', 'tags', 'provider_tag_id',)
    import_id_fields = ('provider_tag_id',)

Admin.py

 class ProviderTagAdmin(ImportExportModelAdmin):
    list_display = ('provider', 'get_tags', 'provider_tag_id')
    search_fields = ['provider',]
    resource_class = ProviderTagResource

    def get_tags(self, obj):
        print(obj.tags)
        return ", ".join([str(p) for p in obj.tags.all()])
admin.site.register(ProviderTag, ProviderTagAdmin)

Solution

  • I cannot provide a direct answer but my suggestion would be to get the example application running.

    You can easily test importing a m2m field. You would have to define a m2m field on BookResource in the core/admin.py file:

    class BookResource(ModelResource):
        categories = fields.Field(
            attribute='categories',
            widget=widgets.ManyToManyWidget(Category, field='name',
                                            separator='|')
        )
    
        class Meta:
            model = Book
    

    Then you can import a sample file such as:

    id,name,author,author_email,imported,published,published_time,price,categories
    1,book1,,[email protected],0,2020-07-21,,10.25,Category1|Category2
    

    At least if you can prove it is working in the example application, then you can hopefully try to debug your implementation.