3

Using Django 3.2, I have used queryset.values() method to get database values in a suitable format to convert it into a Pandas dataframe.

qs = Project.objects.all()
data = qs.values()

This code generated data as following:

<queryset [{'id': 1, 'name': 'Demo project 1', 'credit': 3}, {'id': 2, 'name': 'Demo project 2', 'credit': 2}, {'id': 3, 'name': 'Demo project 3', 'credit': 3}]>

Is it possible to achieve a similar data using Flask with SQLAlchemy. Note that I have used the automap_base to access the database table. The codes are as following:

Database = automap_base()
Database.prepare(my_engine, reflect=True)
Tables = Database.classes
Project = Tables.Project
session_factory = sessionmaker(bind=my_engine)
SessionCon = scoped_session(session_factory)

session = SessionCon()
all_projects = session.query.all()

How can I convert it into a list of dictionaries when lazy loading is enabled? I wish to get data in a format that can be converted into a Pandas dataframe. A demo would be like this list of dictionaries:

[{'id': 1, 'name': 'Demo project 1', 'credit': 3}, {'id': 2, 'name': 'Demo project 2', 'credit': 2}, {'id': 3, 'name': 'Demo project 3', 'credit': 3}]
davidism
  • 121,510
  • 29
  • 395
  • 339
Rifat Rakib
  • 134
  • 7

0 Answers0