Search code examples
sqldjangorawsql

How to check a request.user with raw sql in Django


I want to get data about a Student which is currently logged in

Here is my code:

def profile(request):
    cursor = connection.cursor()
    a = request.user.id
    cursor.execute("SELECT * from Student WHERE ID = a ")

    data = dictfetchall(cursor)
    return render(request, 'personal.html', {'data': data})

in table Student attribute ID is connected with attribute id in tha table auth_user Is it even possible to check? I know that with ORM it is easy to do, but I need to use raw sql


Solution

  • You work with a parameter, so:

    def profile(request):
        with connection.cursor() as cursor:
            cursor.execute('SELECT * FROM Student WHERE ID = %s', [request.user.id])
            data = dictfetchall(cursor)
        return render(request, 'personal.html', {'data': data})

    however using raw queries is often not a good idea.