Thereissoupinmyfly
Thereissoupinmyfly

Reputation: 244

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

Upvotes: 1

Views: 885

Answers (2)

François
François

Reputation: 46

Since _meta.get_all_field_names() is deprecated (Django 1.10), you may use a comprehension list:

[f.name for f in MyModel._meta.get_fields()]

in the short version.

See https://docs.djangoproject.com/en/1.10/ref/models/meta/ for details.

Code become something like that:

field_names = [f.name for f in Property._meta.get_fields()]

Upvotes: 3

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

Upvotes: 2

Related Questions