Created
September 2, 2016 10:08
-
-
Save antfu/e6203ab9ceccbd91caf195f31c7652a2 to your computer and use it in GitHub Desktop.
[Python|SqlAlchemy] as_dict for SqlAlchemy declarative base
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy.ext.declarative import declarative_base | |
class Mixin: | |
def as_dict(self): | |
return {c.name: getattr(self, c.name) for c in self.__table__.columns} | |
def as_clear_dict(self): | |
_dict = {} | |
for c in self.__table__.columns: | |
if c.foreign_keys: | |
continue | |
val = getattr(self, c.name) | |
if val: | |
_dict[c.name] = val | |
return _dict | |
Base = declarative_base(cls=Mixin) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment