Django 使用原生SQL操作sqlite3數據庫

有一些複雜的查詢,用orm實現比較複雜,故可以採用sql語句來實現查詢。

使用遊標實現:

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("select * from COVID_19Analyse_country")
    for row in cursor.fetchall():
        print(row)

複雜的SQL如下:

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("""
        select country.name,tmp.h heal,tmp.c confirm,round(tmp.h/tmp.c,4) healrate
        from COVID_19Analyse_country country,
            (
                select cast(heal as REAL) h,confirm c,country_id
                from COVID_19Analyse_countrydata
                where date = '2020-06-18' and c >1000
                order by h/c
                limit 0,10
            ) tmp
        where tmp.country_id=country.id;
        """)
    for row in cursor.fetchall():
        print(row)

獲取表頭:

    title = []
    for field in cursor.description:
        title.append(field[0])
    print(title)

綜合以上,將數據處理爲一個字典列表形式,類似於Django中的model_to_dict後的格式:

    from django.db import connection
    cursor = connection.cursor()
    cursor.execute("""
        select country.name,tmp.h heal,tmp.c confirm,round(tmp.h/tmp.c,4) healrate
        from COVID_19Analyse_country country,
            (
                select cast(heal as REAL) h,confirm c,country_id
                from COVID_19Analyse_countrydata
                where date = '2020-06-18' and c >1000
                order by h/c
                limit 0,10
            ) tmp
        where tmp.country_id=country.id;
        """)
    title = []
    for field in cursor.description:
        title.append(field[0])
    ans = []
    for row in cursor.fetchall():
        dictTmp = {}
        for i in range(len(title)):
            dictTmp[title[i]] = row[i]
        ans.append(dictTmp)
    print(ans)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章