Search code examples
pythondjangodjango-import-export

Best place to update related fields via django-import-export


In our project, we have to import and export complicated models in *.xls and other formats. django-import-export great tool and helped us. I wrote a lot of code for creating/editing related models vie additional meta fields (two or three levels in deep). I used import_row, import_field, before_import_row and others methods in our base ModelResource.

And now I have little trouble where to place the code for simple logic. We want to update related object's field. For example:

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    author = models.OneToOneField(Author)

I want to export and import (update) author__name via book resource. I tried to write Widget for this field but it wasn't a good idea.

Give me an example how to export end import author__name from BookResource in right way, please.


Solution

  • Sorry for this stupid question (I had a problem with my other code). The solution is very simple.

    class BookResource(Resource):
        author_name = Field(attribute='author__name')
    
        class Meta:
            fields = ('author_name',)
    

    And it works.