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) userna
Solution 1:
You can make use of user.__table__.columns
:
defget_model_dict(model):
returndict((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:
Solution 2:
In most scenarios, column name is fit for them. But maybe you write the code like follows:
class UserModel(BaseModel):
user_id =Column("user_id", INT, primary_key=True)
email =Column("user_email", STRING)
the column.name "user_email" while the field name is "email", the column.name could not work well as before.
There is a another trick by using Python metaclass, the sample code:
Post a Comment for "How To Get Column And Values Dictionary In Sqlalchemy Model?"