我有以下 csv 导出功能来导出 csv 文件中的模型信息。但我试图弄清楚如何显示模型中函数的输出。因此 csv 导出函数显示模型中的所有字段(表中的字段),但不显示模型中函数的输出。
因此,如果我有以下内容:
def avg_tag(self, obj):
bids = Bid.objects.active(user=obj.user.id)
return bids.aggregate(average_price=Avg('list_price'))['average_price']
在模型中
它没有从该函数获得输出。
这是 csv 导出功能操作:
def export_select_fields_csv_action(description="Export selected objects",
fields=None, exclude=None, header=True):
def export_as_csv(modeladmin, request, queryset):
"""
Generic csv export admin action.
based on http://djangosnippets.org/snippets/1697/
"""
opts = modeladmin.model._meta
field_names = [field.name for field in opts.fields]
labels = []
if exclude:
field_names = [v for v in field_names if v not in exclude]
elif fields:
field_names = [k for k, v in fields if k in field_names]
labels = [v for k, v in fields if k in field_names]
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = ('attachment; filename=%s.csv'
% unicode(opts).replace('.', '_'))
writer = csv.writer(response)
if header:
if labels:
writer.writerow(labels)
else:
writer.writerow(field_names)
for obj in queryset:
writer.writerow([unicode(getattr(obj, field)).encode('utf-8')
for field in field_names])
return response
export_as_csv.short_description = description
return export_as_csv
如何更改上述函数,以便将模型中函数的输出输出到 csv 中?谢谢!