为了账号安全,请及时绑定邮箱和手机立即绑定

python + django 多表联合查询方法求教

python + django 多表联合查询方法求教

互换的青春 2019-03-20 11:13:08
python + django 多表联合查询方法求教 
查看完整描述

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})



查看完整回答
反对 回复 2019-03-22
  • 2 回答
  • 0 关注
  • 640 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信