1
我有以下csv導出功能導出csv文件中的模型信息。但我試圖弄清楚如何顯示模型中函數的輸出。因此,CSV導出功能顯示模型中的所有字段從模型中的功能(表中的字段),但不輸出..Django 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被輸出?謝謝!
嘎!打敗我一拳:) – Brandon 2013-02-22 19:28:16
@布蘭登 - 我是否在分階段發揮髒張貼? ;) – 2013-02-22 19:33:32
哈哈。一點也不。最近我剛剛遇到Stack Overflow橫行。 – Brandon 2013-02-22 19:34:57