How to write a CSV file populated by my sqlite3 db?

I am a bit confused about how I will populate the following csv function with information in my models.py for a given user. Can someone point me in the right direction? Do I need to process the information in the separare py file file, or can I do this in my views?

My opinion is to download information

def download(request): response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=UserData.csv' writer = csv.writer(response) writer.writerow(['Date', 'HighBGL', 'LowBGL', 'Diet', 'Weight', 'Height', 'Etc']) writer.writerow(['Info pertaining to date 1']) writer.writerow(['info pertaining to date 2']) return response 

One of the models that I'm interested in saving

 class DailyVital(models.Model): user = models.ForeignKey(User) entered_at = models.DateTimeField() high_BGL = models.IntegerField() low_BGL = models.IntegerField() height = models.IntegerField(blank = True, null = True) weight = models.IntegerField(blank = True, null = True) 
+4
source share
2 answers

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

You can then either manually convert the objects into tuples, or you can use the Django QuerySet values_list with a list of fields to return tuples instead of objects. Sort of:

 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 do not need it in Django, you can also consider the sqlite3 command line -csv .

+1
source

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

First you need an object for the list function:

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

Then you just pass this to the csvwriter with the list (given some list_of_objects that you requested)

 attr_list = ['date', 'high_BGL', 'low_BGL', 'diet', 'weight', 'height'] writer.writerows([object2list(obj, attr_list) for obj in list_of_objects]) 
0
source

All Articles