How to do a costum SQL Query in Django
I have an external database wich is registered in the settings.py. No I want query some information. But it doesn't work. In the Terminal I can see that the query doesn`t start. I hope you can help me.
view.py
from django.db import connections
def userquery(request):
currentuser = request.user
userinfoquery = "SELECT * FROM 'userinformation' WHERE 'username' = %s", [currentuser]
with connections['mysql-server'].cursor() as cursor:
cursor.execute(userinfoquery)
userdata = cursor.fetchall()
return render(request,'account_settings.html', {'userdata' : userdata})
call in html-file
<label>{{userdata.name}}</label>
cursor.fetchall() fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch. And you cannot display tuples as <label>{{userdata.name}}</label>.
You have to loop over the fetchall() data and then pass into the template.