Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get column and values dictionary in SQLAlchemy model?

I have the following table:

Base = declarative_base()
metadata = Base.metadata

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    username = Column(String(255))
    email = Column(String(255))

Is it possible to get a dictionary that for empty record will return something like:

{'id': None, 'username': None, 'email': None}

And if I do:

user = User()
user.username = "testuser"
user.email = "[email protected]"

I want to be able to get the dictionary with the corresponding values. Of course if I save the record I'd expect it to have the id there as well.

like image 360
ddinchev Avatar asked Sep 20 '25 03:09

ddinchev


2 Answers

You can make use of user.__table__.columns:

def get_model_dict(model):
    return dict((column.name, getattr(model, column.name)) 
                for column in model.__table__.columns)

Usage:

user = User()
get_model_dict(user)

There are also other options at:

  • Convert sqlalchemy row object to python dict
like image 104
alecxe Avatar answered Sep 22 '25 16:09

alecxe


this is how.

getattr(User, 'id')
like image 39
Mahmoud Magdy Avatar answered Sep 22 '25 17:09

Mahmoud Magdy