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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With