Using raw SQL in django-rest framework?

2019-07-09 00:14发布

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

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()

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.)

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.

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?

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

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

1条回答
等我变得足够好
2楼-- · 2019-07-09 00:48

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.

查看更多
登录 后发表回答