[Django]-How would I write a CSV file populated with my sqlite3 db?

1👍

First you need to query your django model, something like: DailyVital.objects.all() or DailyVital.objects.filter(user=request.user)

Then you can either transform the objects manually into tuples, or you can use Django QuerySet‘s values_list method with a list of field names to return tuples instead of objects. Something like:

def download(request):
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=UserData.csv'
    writer = csv.writer(response)
    writer.writerow(['Date', 'HighBGL', 'LowBGL', 'Weight', 'Height'])
    query = DailyVital.objects.filter(user=request.user)
    for row in query.values_list('entered_at', 'high_BGL', 'low_BGL', 'weight', 'height'):
       writer.writerow(row)
    return response

If you didn’t need it in Django, you might also consider the sqlite3 command line program’s -csv option.

👤joeln

0👍

An easy way to do this would be to convert your models into a list of lists.

First you need an object to list function:

def object2list(obj, attr_list):
    " returns values (or None) for the object's attributes in attr_list"
    return [getattr(obj, attr, None) for attr in attr_list]

Then you just pass that to the csvwriter with a list comprehension (given some list_of_objects that you’ve queried)

attr_list = ['date', 'high_BGL', 'low_BGL', 'diet', 'weight', 'height']

writer.writerows([object2list(obj, attr_list) for obj in list_of_objects])

Leave a comment