モデル使用

id = 1

User.objects.raw('SELECT id, name FROM user WHERE id= %s', [id])

 

モデル未使用

from django.db import connection

...

id = 1

with connection.cursor() as cursor:
   
cursor.execute('SELECT id, name FROM user WHERE id = %s', [id])
    row = cursor.fetchone()

複数レコードを取得する場合は fetchone ではなく fetchall を使用する。

from django.db import connection

...

id = 1

with connection.cursor() as cursor:
   
cursor.execute('SELECT id, name FROM user WHERE id = %s', [id])
    row = cursor.fetchall()