我的模型:
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'])
资源:
from import_export import resources
from models import TreeNode
class TreeNodeResource(resources.ModelResource):
class Meta:
model = TreeNode
查看:
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
但此代码仅导出存储在数据库中的字段。如何将 pay_progress 属性值添加到导出的报告中?
请您参考如下方法:
您可以利用 dehydrate_<fieldname>方法:
class TreeNodeResource(resources.ModelResource):
pay_progress = fields.Field()
class Meta:
model = TreeNode
def dehydrate_pay_progress(self, node):
return node.pay_progress
我觉得有点乏味;如果有人有更好的解决方案,请毫不犹豫地提出。
编辑: 您可以使用 Field 的命名参数 attribute 来获取对象属性,而无需使用 dehydrate():
class TreeNodeResource(resources.ModelResource):
pay_progress = fields.Field(attribute='pay_progress')
class Meta:
model = TreeNode
也可以follow relationships使用双下划线。
