LEFT JOIN Django ORM

两个表做联合查询,从a, b表中各取一部分字段

将列表记录转为字典:

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

 

我这里value是传进来的参数,你可以按照需要的方式写SQL语句。

from django.db import connection
cursor=connection.cursor()
where = 'where project_name=' + "'" + value + "'"
cursor.execute('select a.name, b.age from personal a \
    left join information b on a.name=b.name ' + where)
rows=dictfetchall(cursor)

 

实际效果看官方给的样例吧:

>>> from django.db import connection
>>> cursor=connection.cursor()
>>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
>>> cursor.fetchall()
((54360982, None), (54360880, None))

>>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
>>> dictfetchall(cursor)
[{'parent_id': None, 'id': 54360982}, {'parent_id': None, 'id': 54360880}]

 

参考:

Django之ORM执行原生sql语句

https://docs.djangoproject.com/en/3.1/topics/db/sql/   要说专业,还是得官方文档

 

posted @ 2020-09-25 19:58  船长博客  阅读(1399)  评论(0编辑  收藏  举报
永远相信美好的事情即将发生!