How to export property values with django-import-export
Asked Answered
H

1

6

My model:

class TreeNode(MPTTModel):
    ...
    @property
    def pay_progress(self):
        return "{}/{}".format(self.annuities.exclude(fact_date=None).aggregate(Sum('total'))['total__sum'] or 0,
                             self.annuities.aggregate(Sum('total'))['total__sum'])

Resources:

from import_export import resources
from models import TreeNode


class TreeNodeResource(resources.ModelResource):
    class Meta:
        model = TreeNode

View:

def export_treenode_csv(request):
    treenode_resource = TreeNodeResource()
    dataset = treenode_resource.export()
    response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="TreeNode.xls"'

    return response

But this code exports only fields stored in database. How to add pay_progress property value to the exported report?

Hooge answered 18/8, 2016 at 13:0 Comment(0)
E
15

You can take advantage of dehydrate_<fieldname> method:

class TreeNodeResource(resources.ModelResource):
    pay_progress = fields.Field()

    class Meta:
        model = TreeNode

    def dehydrate_pay_progress(self, node):
        return node.pay_progress

I find it a bit tedious; if someone has a better solution don't hesitate to posit it.

Edit: you can use the named parameter attribute of a Field to get an object attribute/property without using dehydrate():

class TreeNodeResource(resources.ModelResource):
    pay_progress = fields.Field(attribute='pay_progress')

    class Meta:
        model = TreeNode

It is also possible to follow relationships using a double underscore.

Engine answered 15/3, 2017 at 17:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.