【问题标题】:Reports With Django使用 Django 报告
【发布时间】:2016-08-22 12:09:27
【问题描述】:

我正在尝试在 django 中创建一个非常高级的查询,但我在这样做时遇到了问题,我可以使用基本的:

for obj in Invoice.objects.filter():

但是如果我尝试将其移至原始 PostgreSQL 查询中,我会收到一个错误,告诉我该关系不存在我做错了什么,我正在关注 django 文档上的Preforming raw SQL,但我一直收到同样的错误

完整代码:

def csv_report(request):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'

writer = csv.writer(response, csv.excel)
response.write(u'\ufeff'.encode('utf8'))
writer.writerow([
    smart_str(u"ID"),
    smart_str(u"value"),
    smart_str(u"workitem content type"),
    smart_str(u"created date"),
    smart_str(u"workitem.id"),
    smart_str(u"workitem"),
    smart_str(u"workitem_content_type"),
])
for obj in Invoice.objects.raw('SELECT * from twm_Invoice'):
    writer.writerow([
        smart_str(obj.pk),
        smart_str(obj.value),
        smart_str(obj.workitem_content_type),
        smart_str(obj.created_date),
        smart_str(obj.workitem_id),
        smart_str(obj.workitem),
        smart_str(obj.workitem_content_type),
    ])
return response

我现在尝试在模型名称前面使用该应用程序,但似乎没有一个可以工作。

谢谢你

【问题讨论】:

  • 为什么你不能使用普通过滤器?这是实际的表名吗?
  • @DanielRoseman 我正在尝试使用数据库从大约 5 个表中获取数据。我没有过滤器功能能够做到这一点。是的,它的真名:)

标签: python django postgresql


【解决方案1】:

尝试直接在数据库中运行你的原始 sql。我猜你的表名不正确,通常它们是小写的

顺便说一句.. 我希望你有一个很好的理由使用原始 sql 查询而不是很棒的 ORM ;)

【讨论】:

  • ORM 是否能够进行大/多表查询?嗯,也许我会读一下。谢谢。
  • ORM 可能会生成与您编写的相同的查询,但使用 ORM 更易于阅读、维护、调试、测试、重用您的代码。但有时您有一个非常复杂的查询更好使用原始 sql。这取决于你:)
猜你喜欢
  • 2011-11-27
  • 2017-06-27
  • 2010-11-08
  • 2021-02-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多