在Django-rest框架中使用原始SQL? [英] Using raw SQL in django-rest framework?

查看:446
本文介绍了在Django-rest框架中使用原始SQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Django 1.8与Postgres 9.4后端一起使用,该后端具有表和实例化视图。

I am using Django 1.8 with a Postgres 9.4 back-end with tables and materialized views.

我有一个名为 spending 的80GB表,其中包含支出项,每个支出项都有组织代码和地区代码:

I have an 80GB table called spending with spending items, each with an organisation code and a region code:

class Prescription(models.Model):
  region = models.ForeignKey(Region)
  organisation = models.ForeignKey(Organisation)
  month = models.DateField()
  amount = models.FloatField()

我也有一个 spending_by_region 的物化视图,该视图是从 spending 表生成的:

I also have a materialized view for spending_by_region, generated from the spending table:

CREATE MATERIALIZED VIEW spending_by_region AS 
      SELECT region, month, SUM(amount) AS amount 
      FROM spending
      GROUP BY month, region_id

(我使用的是物化视图,因为数据非常大且静态,实际上是一个数据仓库。)

(I'm using the materialized views because the data is very large and static, effectively a data warehouse.)

我的某些Django视图使用物化视图,例如我对每个地区的看法。在这些情况下,我使用原始SQL来运行 select * from working_by_region,其中region = 123 ,因为Django的ORM当然不了解物化视图。

Some of my Django views use the materialized views, e.g. my view for each region. In these cases I use raw SQL to run select * from spending_by_region where region=123, because of course Django's ORM doesn't know about materialized views.

现在,我想开始为我的应用程序实现API。我听说过有关django-rest-framework的好消息,但是在序列化之前是否可以使用原始SQL查询获取数据?

Now I want to start implementing an API for my application. I have heard good things about django-rest-framework, but will it be possible to use raw SQL queries to get the data before serializing it?

例如,如果我想要一个名为 / spending_by_region / 123 的API方法,是否可以运行与上面相同的查询?

For example, if I want an API method called /spending_by_region/123, will it be possible to run the same query as above?

我发现了此示例,但是它仍然与Model字段相关,而不是纯粹的原始SQL。

I found this example, but it's still tied to a Model field, rather than being purely raw SQL.

推荐答案

Django-Rest-Framework在Django应用程序的顶部运行,您可以为所需的模型设置自定义管理器并执行原始查询,或者直接使用Django ORM中的 .raw()方法。就像任何其他Django应用程序一样,但是您获得了视图和序列化程序来响应JSON对象。

Django-Rest-Framework works at the top of a Django Application, You can set a custom manager to the models you want and execute raw queries, or simply use the .raw() method from Django's ORM. It's like any other Django application, but you gain the views and serializers to respond JSON objects.

这篇关于在Django-rest框架中使用原始SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆