TAGS :Viewed: 4 - Published at: a few seconds ago

[ Django export model to csv without knowing the field names ]

I've fairly new at django. What I'm trying to do is export the contents of a model to csv. I have managed to do it when I specify all the model fields names but I want to be able to use it with multiple models and therefore would like to be able to export the data without specifying the model field names.

Sorry if this is very noobish. I acknowledge my lack of knowledge in this area.

here is what I have so far.

def csv_download(request):
    #
    #exports the properties to a csv file
    #
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="properties.csv"'
    property_list = Property.objects.all()
    writer = csv.writer(response)
    Property._meta.get_all_field_names()
    field_names = Property._meta.get_all_field_names()
    writer.writerow(field_names)
    for each in property_list:
        row=[]
        for name in field_names:
            row.append(Property._______.value())
        writer.writerow(row)
    return response

This is what I adjusted it to after Yuji 'Tomita' Tomita's help

def csv_download(request):
#
#exports the properties to a csv file
#
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="properties.csv"'
property_list = Property.objects.all()
writer = csv.writer(response)
Property._meta.get_all_field_names()
field_names = Property._meta.get_all_field_names()
writer.writerow(field_names)
for property in property_list:
    row =[]
    for name in field_names:
        try:
            row.append(str(getattr(property, name)))
        except:
            row.append(" ")
    writer.writerow(row)
return response

Answer 1


attribute_value = getattr(Property, name)

Note that some of these fields will return objects you will want to convert to strings. i.e. row.append(str(getattr(...)))