Skip to content

Instantly share code, notes, and snippets.

@antfu
Created September 2, 2016 10:08
Show Gist options
  • Save antfu/e6203ab9ceccbd91caf195f31c7652a2 to your computer and use it in GitHub Desktop.
Save antfu/e6203ab9ceccbd91caf195f31c7652a2 to your computer and use it in GitHub Desktop.
[Python|SqlAlchemy] as_dict for SqlAlchemy declarative base
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