Django-import-export - export from model's functions?
Asked Answered
T

3

6

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

Tulatulip answered 15/9, 2014 at 13:40 Comment(0)
B
11

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

Betz answered 15/9, 2014 at 14:18 Comment(6)
works as requested - thank you! The "dehydrate" terminology really put me off.Tulatulip
now for a bonus :) how do I order the output so this new field is the last column (without explicitly specifying EVERY field)?Tulatulip
read the link, manual is very sparse... from what I understand I do have to list all the output fields in desired order?Tulatulip
Yes, unfortuanately you must list all the fields that you want to export there -- of course you could also do some other tricks for instance redefine get_export_order in your BookResource so that it returns firstowrd last (check the source here github.com/bmihelac/django-import-export/blob/master/…)Betz
wow, lots more work... think I'll keep it simple. Thanks again!Tulatulip
Thank you! updated link django-import-export.readthedocs.io/en/latest/…Saury
T
3

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
Tericaterina answered 26/8, 2017 at 8:35 Comment(1)
works like charm. Didn't expect can be that simple. Thanks, mate.Debutant
S
0

Just in case you need to get the full URL of the field and based on @Serafeim's solution

class CompanyModelResource(ModelResource):

    def dehydrate_local_logo(self, company):
        if company.local_logo and hasattr(company.local_logo, 'url'):
            return company.local_logo.url
        return company.local_logo

    class Meta:
        model = Company
Saury answered 15/3, 2021 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.