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

前端 未结 2 1974
清酒与你
清酒与你 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...)
    

提交回复
热议问题