dlyxzen
dlyxzen

Reputation: 243

Generating CSV through Django View

There are a few threads already in regards to generating CSV file in a Django view but none that really suit my situation (and work for me).

As I have created a sort of , query builder for my end user, which allows them to select what fields are included in the queryset, so the the fields being selected may vary from query to query, hence I am not able to 'hard-code' my table headings etc:

My Models.py

class Customers(models.Model):
    firstname = models.CharField(max_length=100)
    middlename = models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)
    nickname = models.CharField(max_length=100)    

Basically I have 1 dictionary, and 2 arrays building the queryset, this comes in through my request.POST.

customers = Customers.objects.all().filter(**filargs).order_by(*ordargs).values(*selargs)

Lets say for example, the end user only wants to select the fields 'firstname' and 'lastname', I simply want to generate a CSV like the following

First Name    Last Name
John          Johnson
Ted           Samson

As I have seen from the Django documentation that you can create rows by using the following code

writer.writerow(['First Name','Last Name'])

However as the fields being selected in the queryset can differ from query to query, I need a dynamic way of doing this. I tried the following, but did not seem to work.

writer.writerow(selargs)  << selargs being my select field list

In regards to writing the actual records (not the field names) , I tried something like this, but obviously the output I got was incorrect.

for customer in customers:
    for value in customer:
        writer.writerow(value)

But as you would expect this gave me a separate row for every field value in each record. Is there some sort of 'write.writecell' or something along those lines?

As help would be greatly appreciated. I'm sure there is a easy solution to this.

Thanks,

Upvotes: 1

Views: 601

Answers (1)

Armance
Armance

Reputation: 5390

The following takes in a Django queryset and spits out a CSV file.

Usage::

from utils import dump2csv

from dummy_app.models import *

qs = DummyModel.objects.all()

dump2csv.dump(qs, './data/dump.csv')

The script:

import csv
from django.db.models.loading import get_model

def dump(qs, outfile_path):

    model = qs.model
writer = csv.writer(open(outfile_path, 'w'))

headers = []
for field in model._meta.fields:
    headers.append(field.name)
writer.writerow(headers)

for obj in qs:
    row = []
    for field in headers:
        val = getattr(obj, field)
        if callable(val):
            val = val()
        if type(val) == unicode:
            val = val.encode("utf-8")
        row.append(val)
    writer.writerow(row)

Upvotes: 1

Related Questions