Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export property values with django-import-export

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?

like image 700
tonyjasta Avatar asked Jan 06 '23 12:01

tonyjasta


1 Answers

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.

like image 137
DurandA Avatar answered Jan 13 '23 14:01

DurandA