Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Django中获取SQL原始查询的值?_Django - Fatal编程技术网

如何在Django中获取SQL原始查询的值?

如何在Django中获取SQL原始查询的值?,django,Django,我想使用原始sql查询获取特定字段的总和: total_profit = queryset.raw('SELECT SUM("products_product"."profit") AS Total_Profit FROM "products_product"') 使用total\u profice.columns,它返回['total\u profice']。虽然,我不知道如何访问它 如果我尝试总利润[“总利润”],我会得到以下错误: InvalidQuery: Raw query must

我想使用原始sql查询获取特定字段的总和:

total_profit = queryset.raw('SELECT SUM("products_product"."profit") AS Total_Profit FROM "products_product"')
使用
total\u profice.columns
,它返回
['total\u profice']
。虽然,我不知道如何访问它

如果我尝试
总利润[“总利润”]
,我会得到以下错误:

InvalidQuery: Raw query must include the primary key
我知道我可以用Django ORM获得同样的结果:

total_profit = queryset.aggregate(total_profit=Sum("profit"))

您需要将其作为对象访问。像这样的<代码>总利润。总利润。另外,我不确定
queryset.raw()
的语法是否正确,因为我总是以
model\u name.objects.raw()
为例。而且总是用这种格式

引用我读过的一个例子。你应该试试这样的东西

>>> people = Person.objects.raw('SELECT *, age(birth_date) AS age FROM myapp_person')
>>> for p in people:
...     print("%s is %s." % (p.first_name, p.age))
John is 37.
Jane is 42.
...
你可以从网站上了解更多