Getting data from MySQL table with 25+ columns using django model

Question:

I have a MySQL db (companies_data) with 4 tables (all_users, freq_user, special_users, products). all_users table has 27 columns and thousands of rows, I use that data to feed my machine learning algorithms.

I’m using python, django rest_framework for backend.

Now I wanted to get those data using django model and convert it into pandas dataframe so that I can predict and add the predictions to the other tables. Is there a easy way to get all the data using django model?

Now I’m using raw SQL query with all the column names to get the data.

Asked By: XAVIXXVI

||

Answers:

Do you have a django-model for these tables?
Generally speaking, you can have a django model for each of the tables, then build the queryset for what fields you want (you can also filter) and that’s it.

import pandas as pd
import datetime
from myapp.models import BlogPost


# limit which fields
queryset = User.objects.filter(...).annotate(...).values_list('f1','f2',...)
df = pd.DataFrame(list(queryset), columns=['f1','f2',...]) 

Answered By: DanielM