Search code examples
djangodjango-admindjango-import-export

Django-import-export - export from model's functions?


For a Django model I'm using django-import-export package.

The manual says I can export fields that are not existing in the target model like so:

from import_export import fields

class BookResource(resources.ModelResource):
    myfield = fields.Field(column_name='myfield')

    class Meta:
        model = Book

http://django-import-export.readthedocs.org/en/latest/getting_started.html

How do I export the output of functions from the model? e.g. Book.firstword()


Solution

  • Here's how you should do it (check this out https://django-import-export.readthedocs.org/en/latest/getting_started.html#advanced-data-manipulation):

    from import_export import fields, resources
    
    class BookResource(resources.ModelResource):
        firstword = fields.Field()
    
        def dehydrate_firstword(self, book):
            return book.firstword()
    
        class Meta:
            model = Book
    

    Update to answer OP comment

    To return fields in a particular order, you can user the export_order Meta option (https://django-import-export.readthedocs.org/en/latest/api_resources.html?highlight=export_order#import_export.resources.ResourceOptions).