0

Hi I am writing a Django view which generates a csv file. Pretty straightforward. In my view I have:

def mysearch(request, exportCSV):
    ...
    if 'q' in request.GET or exportCSV:
        results_list = request.session['results_list']
    ...
    if exportCSV:
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename=myfile.csv'
        writer = csv.writer(response)

        # write field titles                
        writer.writerow(['name_of_firstfield', 'name_of_secondfield', ... ,])

        for row in results_list: 
            # write row content
            writer.writerow([row.firstfield, row.secondfield, ... , ])
        return response     

There are actually two questions here:

  1. How do I output the name of a model field as text so I can write the field titles to the first row.

  2. How can I avoid specifying each field (considering I have a lot of fields) for both lines. I basically want to say for each row, output each field name then output each piece of data.

Can I somehow use getattr here?.

1 Answer 1

2

Have a look at this snippet as a example, you can access a models field names via model._meta.fields and you can use getattr() to get the value of a field for a given object. e.g.

fields = ct_object._meta.fields

writer = csv.writer(response)
writer.writerow([field.column for field in fields])

for object in objects_to_export:
    writer.writerow([getattr(object, field.name) for field in fields])
Sign up to request clarification or add additional context in comments.

2 Comments

+1, except better to use field.name rather than column as the header.
Good answer. However, my query is quite complex and involves multiple joins, so I think I'm stuck with listing the required fields at some point in the process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.