2 回答
TA贡献1829条经验 获得超7个赞
如果你觉着使用自带ORM查询费劲的话。直接获取数据库连接,然后执行sql语句。
def my_custom_sql():
from django.db import connection, transaction
cursor = 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 connections
cursor = connections['my_db_alias'].cursor()
# Your code here...
transaction.commit_unless_managed(using='my_db_alias')
通常我们不需要手动调用
transaction.commit_unless_managed(
),我们可以这样做:
@commit_on_success
def my_custom_sql_view(request, value):
from django.db import connection, transaction
cursor = connection.cursor()
# Data modifying operation
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [value])
# Since we modified data, mark the transaction as dirty
transaction.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})
添加回答
举报