Skip to content

Instantly share code, notes, and snippets.

@magne4000
Last active June 8, 2016 07:49
Show Gist options
  • Save magne4000/31a4b6bd55baa9a4bfe51bf7ebcfc6ce to your computer and use it in GitHub Desktop.
Save magne4000/31a4b6bd55baa9a4bfe51bf7ebcfc6ce to your computer and use it in GitHub Desktop.
SQLAlchemy Mixin adding as_dict() function. Supports inheritance
from itertools import chain
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Mixin(object):
def as_dict(self):
tables = [base.__table__ for base in self.__class__.__bases__ if base not in [Base, Mixin]]
tables.append(self.__table__)
return {c.name: getattr(self, c.name) for c in chain.from_iterable([x.columns for x in tables])}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment