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/   要說專業,還是得官方文檔

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM