Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()

like image 939
Alveoli Avatar asked Sep 15 '14 13:09

Alveoli


2 Answers

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).

like image 115
Serafeim Avatar answered Nov 15 '22 21:11

Serafeim


There is one more solution with less code, than that suggested by Serafeim:

from import_export import fields, resources

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

    class Meta:
        model = Book
like image 3
Petr Dlouhý Avatar answered Nov 15 '22 21:11

Petr Dlouhý