Home > Back-end >  Django Rest Framework complex SQL query
Django Rest Framework complex SQL query

Time:07-01

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?

CodePudding user response:

You can use the raw function to make it

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

CodePudding user response:

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