Django-import-export - export from model functions?

For the Django model, I use the django-import-export package.

The manual says that I can export fields that do not exist in the target model, for example:

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 output from a model? for example Book.firstword ()

+3


source to share


2 answers


This is how you should do it (check 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's comment

To return fields in a specific order, you can use the export_order

Meta option ( https://django-import-export.readthedocs.org/en/latest/api_resources.html?highlight=export_order#import_export.resources.ResourceOptions ).

+5


source


There is another solution with less code than Serafeim's suggestion:



from import_export import fields, resources

class BookResource(resources.ModelResource):
    firstword = fields.Field(attribute='firstword')

    class Meta:
        model = Book

      

+1


source







All Articles