Reputation: 1202
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()
Upvotes: 6
Views: 3608
Reputation: 2626
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
Upvotes: 0
Reputation: 927
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
Upvotes: 3
Reputation: 15084
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).
Upvotes: 11