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

前端 未结 2 1969
清酒与你
清酒与你 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:15

    You need to use Django's built in QuerySet API. More information on it can be seen here. Once you create a QuerySet you can then use pandas read_sql_query method to construct the data frame. The simplest way to construct a QuerySet is simply query the entire database which can be done like so:

    db_query = YourModel.objects.all() 
    

    You can use filters which are passed in as args when querying the database to create different QuerySet objects depending on what your needs are.

    Then using pandas you could do something like:

    d_frame = pandas.read_sql_query(db_query, other_args...)
    
    0 讨论(0)
  • 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'))) 
    
    0 讨论(0)
提交回复
热议问题