python - 我将如何编写一个用我的 sqlite3 数据库填充的 CSV 文件?

标签 python django csv sqlite

对于如何使用给定用户的 models.py 中的信息填充以下 csv 函数,我有点困惑。谁能指出我正确的方向?我需要在单独的 py 文件中处理信息,还是可以在我的 View 中处理?

我查看下载信息

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)

最佳答案

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

然后您可以手动将对象转换为元组,或者您可以使用 Django QuerySetvalues_list method带有字段名称列表以返回元组而不是对象。像这样的东西:

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 选项。

关于python - 我将如何编写一个用我的 sqlite3 数据库填充的 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12083081/

相关文章:

python - 如何为 Keras 实现 Beholder(Tensorboard 插件)?

Python 子进程将输出返回为 stderr

django - Heroku 上的内存监控

r - 无法使用 spark_read_csv() 将 csv 读入 Spark

python - 为什么 dill 无论如何都会通过引用转储外部类?

python - 根据其他列中的值对列中数据框行的子集应用函数

csv - 无需 Stata 软件即可将 dta 文件转换为 csv

javascript - 在 NodeJS 中使用变换/双工流

Django is_staff 权限装饰器

python - 从 Django 应用程序触发分布式异步处理的良好架构是什么?