How to read sql query to pandas dataframe / python / django

前端 未结 2 2086
清酒与你
清酒与你 2021-02-07 23:56

I\'m using this below in views.py to get app

from django.db import connection

def test(request):

    cursor = connection.cursor()
    sql = \"         


        
2条回答
  •  广开言路
    2021-02-08 00:23

    I think aus_lacy is a bit off in his solution - first you have to convert the QuerySet to a string containing the SQL backing the QuerySet

    from django.db import connection
    
    query = str(ModelToRetrive.objects.all().query)
    df = pandas.read_sql_query(query, connection)
    

    Also there is a less memory efficient but still valid solution:

    df = DataFrame(list(ModelToRetrive.objects.values('id','some_attribute_1','some_attribute_2'))) 
    

提交回复
热议问题