千巷猫影
如果你觉着使用自带ORM查询费劲的话。直接获取数据库连接,然后执行sql语句。def my_custom_sql():from django.db import connection, transactioncursor = connection.cursor()# 数据修改操作——提交要求cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])transaction.commit_unless_managed()# 数据检索操作,不需要提交cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])row = cursor.fetchone()return row多数据from django.db import connectionscursor = connections['my_db_alias'].cursor()# Your code here...transaction.commit_unless_managed(using='my_db_alias')通常我们不需要手动调用transaction.commit_unless_managed(),我们可以这样做:@commit_on_successdef my_custom_sql_view(request, value):from django.db import connection, transactioncursor = connection.cursor()# Data modifying operationcursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [value])# Since we modified data, mark the transaction as dirtytransaction.set_dirty()# Data retrieval operation. This doesn't dirty the transaction,# so no call to set_dirty() is required.cursor.execute("SELECT foo FROM bar WHERE baz = %s", [value])row = cursor.fetchone()return render_to_response('template.html', {'row': row})