我想将我的表导出到csv文件中。 但是我表中的一些字段是属性。
例如:' current_tobe_payed',' current_balance',' current_period',' total_payment',' total_discount&#39 ;
def export_leaseterm_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="leaseterm.csv"'
writer = csv.writer(response)
writer.writerow(['lease', 'increase', 'amount', 'is_terminated', 'current_tobe_payed', 'current_balance', 'current_period','total_payment', 'total_discount'])
leaseterms = LeaseTerm.objects.all().values_list('start_period', 'end_period', 'lease', 'increase', 'amount', 'is_terminated', 'current_tobe_payed', 'current_balance', 'current_period','total_payment', 'total_discount')
for leaseterm in leaseterms:
writer.writerow(leaseterm)
return response
我正在Cannot resolve keyword 'current_tobe_payed' into field.
我如何克服它?
更新:
我已根据回答更新了视图:
def export_leaseterm_csv(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="leaseterm.csv"'
writer = csv.writer(response)
leaseterms = serializers.serialize( "python", LeaseTerm.objects.all())
for leaseterm in leaseterms:
writer.writerow([value[0] for value in leaseterm])
return response
收到的输出
F,M,P F,M,P F,M,P F,M,P F,M,P
如果预期是:
33 8788 -6105.00 0 0 6105.00 555.00 False True False
28 4545 -5537.00 1120.00 15.00 6657.00 556.00假真假
32 6789 -3108.00 0 0 3108.00 777.00 False True False
34 2222 0.00 0 0 0.00 777.00 False True False
答案 0 :(得分:1)
显然,您所说的属性已启用current_tobe_payed
。属性不能在values_list调用中使用。将您的代码更改为:
from django.core import serializers
data = serializers.serialize( "python", LeaseTerm.objects.all() )
for leaseterm in data:
writer.writerow([value for value in leaseterm['fields'].values()])
这个序列化程序从我们的模型对象创建一个标准的python对象,它允许我们遍历它们的字段。我们从列表理解中得到一些帮助。