Django: Use variable names instead of %s
Im passing multiple parameter into a raw sql statement, for each parameter im using %s Is it possible to use the variable name instead of multiple %s
Example:
man = "John"
wife = "Jane"
query = "SELECT * FROM person WHER开发者_运维知识库E name = %s and wife = %s"
cursor.execute(query, [man, wife])
Is it a model you are querying?
Looking at the docs explaining the raw() manager
raw() automatically maps fields in the query to fields on the model.
this should be as easy as:
Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')
DB API 2.0 defines following parameter styles
'qmark'
Question mark style, e.g.'...WHERE name=?'
'numeric'
Numeric, positional style, e.g.'...WHERE name=:1'
'named'
Named style, e.g.'...WHERE name=:name'
'format'
ANSI C printf format codes, e.g.'...WHERE name=%s'
'pyformat'
Python extended format codes, e.g.'...WHERE name=%(name)s'
Now, not all databases implement all of them. Check if DB engine you're using does support pyformat
.
精彩评论