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

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

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

慕的地10843 2019-03-13 14:09:27
python + django 多表联合查询方法求教
查看完整描述

2 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

如果你觉着使用自带ORM查询费劲的话。直接获取数据库连接,然后执行sql语句

1

2

3

4

5

6

7

8

9

10

11

12

13

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

多数据

1

2

3

4

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(                ),我们可以这样做:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

@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-18
  • 2 回答
  • 0 关注
  • 670 浏览
慕课专栏
更多

添加回答

举报

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