Django Rest Framework complex SQL query

Viewed 47

I was asked to create the backend of a project using Django (the frontend is angular). So I thought about using rest framework but I'm a total beginner and raw sql queries are needed for this project. To be more precise it's a complex query that needs many tables: they provided the sql script that I need to use it directly.

My question is does rest framework allow such raw queries (because I was not able to find a tutorial about that) or do I need something else?

Edit for further explanation: I'm I able to return complex queries in rest framework as a GET request for example? Any help is appreciated.

2 Answers

You can use the raw function to make it

Model.objects.raw("WRITE YOUR SQL HERE")

You can use cursor connection for direct execute SQL query.

from django.db import connection

def my_query(self):
    with connection.cursor() as cursor:
    cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
    cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
    row = cursor.fetchall()

return row
Related