Ilya Bibik
Ilya Bibik

Reputation: 4124

How to print model properties to excel?

I want to export my table into the csv file . But some of the fields in my table are properties.

For example those: 'current_tobe_payed', 'current_balance', 'current_period','total_payment', 'total_discount'

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

I am getting Cannot resolve keyword 'current_tobe_payed' into field.

How Can I overcome it?

UPDATE:

I have updated the view based on answer:

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

The output received

f,m,p f,m,p f,m,p f,m,p f,m,p

When expected is:

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 False True False

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

Upvotes: 1

Views: 43

Answers (1)

e4c5
e4c5

Reputation: 53734

Clearly current_tobe_payed is on for the properties that you speak of. A property cannot be used in a values_list call. Change your code to:

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()])

This serializer creates a standard python object from our model object which allows us to iterate through their fields. And we get a little help from a list comphrehension.

Upvotes: 1

Related Questions