如何编写填充了我的sqlite3 db的CSV文件?

时间:2012-08-23 00:07:21

标签: python django csv sqlite

我对如何使用models.py中给定用户的信息填充以下csv函数感到困惑。谁能指出我正确的方向?我是否需要在separare py文件中处理信息,还是可以在我的视图中进行处理?

我下载资讯的观点

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

其中一个模型的信息我对保存感兴趣

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)

2 个答案:

答案 0 :(得分:1)

首先,您需要查询django模型,例如:DailyVital.objects.all()DailyVital.objects.filter(user=request.user)

然后你可以手动将对象转换为元组,或者你可以使用带有字段名列表的Django QuerySet的{​​{3}}来返回元组而不是对象。类似的东西:

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

如果你在Django中不需要它,你也可以考虑sqlite3命令行程序的-csv选项。

答案 1 :(得分:0)

一种简单的方法是将模型转换为列表列表。

首先,您需要一个列出功能的对象:

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]

然后你将它传递给具有列表理解的csvwriter(给定一些你查询过的list_of_objects

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

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