[Answered ]-Django doesn't use pyodbc as python does

1👍

Finally my problem was that I wanted to open a cursor from a secondary db, not the default one, so the mistake was here:

from django.db import connection
cursor = connection.cursor()

It should be:

from django.db import connections  # instead of connection
cursor = connections['second_db'].cursor()  # using the proper db

1👍

Django’s execute format is slightly different. Try this?

cursor.execute("SELECT id FROM schema.dbo.mytable WHERE num = %s", [obj.num])

This will also eliminate a possible SQL Injection attack vector. You probably also want to change your pyodbc query to use bound parameters:

cursor.execute("SELECT id FROM schema.dbo.mytable WHERE num = ?", foo.num)

Good luck!

Leave a comment