$ ls ~yifei/notes/

django dump to csv

Posted on:

Last modified:

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

def dump(qs, outfile_path):
    """
    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')
    
    Based on a snippet by zbyte64::
        
        http://www.djangosnippets.org/snippets/790/
    """
    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)
WeChat Qr Code

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.

友情链接: MySQL 教程站