[Sqlalchemy-tickets] Issue #3976: Built-in way to convert an ORM object (i.e. result of an ORM quer
Brought to you by:
zzzeek
From: Markus M. <iss...@bi...> - 2017-05-02 11:52:51
|
New issue 3976: Built-in way to convert an ORM object (i.e. result of an ORM query) to a Python dictionary https://bitbucket.org/zzzeek/sqlalchemy/issues/3976/built-in-way-to-convert-an-orm-object-ie Markus Meskanen: I suggest adding something that allows us to convert ORM objects directly into dictionaries like this: ``` #!python class User(Base): __tablename__ = 'user' id = Column(Integer, primary_key=True) name = Column(Text, required=True) birth_year = Column(Integer) user = session.query(User).filter(User.birth_year==1996).one() return dict(user) ``` This would not only allow extremely easy integration with JSON APIs, but sometimes it's better to handle these objects as dicts for speed etc. Some things to consider: - Recursion; what to do with relationships? Should one-to-many convert to a dict of lists? What if all of those many have more "sub" lists? - Method of converting: 1. Support `dict(obj)`, integrates neatly into Python and this way it supports more than just `dict()`, like custom mapping classes 2. Add a `to_dict()` method to the declarative base class. I like this the *least*, because an object shouldn't know how to convert itself into everything in the world 3. A custom function like `sqlalchemy.orm.to_dict(obj)`. Imo better than #2, and it doesn't clutter the class either. - Ignore fields, i.e. "convert this object to a dict, but ignore `id` column" |