Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert SQLAlchemy row object to a Python dict?

Is there a simple way to iterate over column name and value pairs?

My version of SQLAlchemy is 0.5.6

Here is the sample code where I tried using dict(row):

import sqlalchemy from sqlalchemy import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker  print "sqlalchemy version:",sqlalchemy.__version__   engine = create_engine('sqlite:///:memory:', echo=False) metadata = MetaData() users_table = Table('users', metadata,      Column('id', Integer, primary_key=True),      Column('name', String), ) metadata.create_all(engine)   class User(declarative_base()):     __tablename__ = 'users'          id = Column(Integer, primary_key=True)     name = Column(String)          def __init__(self, name):         self.name = name  Session = sessionmaker(bind=engine) session = Session()  user1 = User("anurag") session.add(user1) session.commit()  # uncommenting next line throws exception 'TypeError: 'User' object is not iterable' #print dict(user1) # this one also throws 'TypeError: 'User' object is not iterable' for u in session.query(User).all():     print dict(u) 

Running this code on my system outputs:

Traceback (most recent call last):   File "untitled-1.py", line 37, in <module>     print dict(u) TypeError: 'User' object is not iterable 
like image 779
Anurag Uniyal Avatar asked Dec 24 '09 12:12

Anurag Uniyal


People also ask

What does SQLAlchemy all () return?

As the documentation says, all() returns the result of the query as a list.

How do I update a row in SQLAlchemy?

Update a row entry in SQLAlchemyGet the books to table from the Metadata object initialized while connecting to the database. Pass the update query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.

What is _sa_instance_state?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.


1 Answers

You may access the internal __dict__ of a SQLAlchemy object, like the following:

for u in session.query(User).all():     print u.__dict__ 
like image 187
hllau Avatar answered Sep 22 '22 03:09

hllau