Created
August 28, 2015 20:18
-
-
Save dpwrussell/60c00bc4e661b4bced7a to your computer and use it in GitHub Desktop.
MarshmallowSqlAlchemy's issue with overriden ids not being serialized
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
import sqlalchemy as sa | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.orm import scoped_session, sessionmaker, relationship | |
from sqlalchemy.ext.hybrid import hybrid_property | |
from marshmallow_sqlalchemy import ModelSchema | |
engine = sa.create_engine('sqlite:///:memory:') | |
session = scoped_session(sessionmaker(bind=engine)) | |
Base = declarative_base() | |
class Person(Base): | |
__tablename__ = 'person' | |
type = sa.Column(sa.String(50)) | |
__mapper_args__ = { | |
'polymorphic_identity': 'person', | |
'polymorphic_on': type | |
} | |
id = sa.Column(sa.Integer, primary_key=True) | |
name = sa.Column(sa.String) | |
def __repr__(self): | |
return '<Person(name={self.name!r})>'.format(self=self) | |
class Author(Person): | |
__tablename__ = 'authors' | |
__mapper_args__ = { | |
'polymorphic_identity': 'author' | |
} | |
id = sa.Column(sa.Integer, sa.ForeignKey('person.id'), primary_key=True) | |
featured = sa.Column(sa.Boolean) | |
def __repr__(self): | |
return '<Author(name={self.name!r})>'.format(self=self) | |
class Book(Base): | |
__tablename__ = 'books' | |
id = sa.Column(sa.Integer, primary_key=True) | |
name = sa.Column(sa.String) | |
author_id = sa.Column(sa.Integer, sa.ForeignKey('authors.id')) | |
author = relationship('Author', backref='books') | |
Base.metadata.create_all(engine) | |
class PersonSchema(ModelSchema): | |
class Meta: | |
model = Person | |
sqla_session = session | |
class AuthorSchema(ModelSchema): | |
class Meta: | |
model = Author | |
sqla_session = session | |
class BookSchema(ModelSchema): | |
class Meta: | |
model = Book | |
sqla_session = session | |
person_schema = PersonSchema() | |
author_schema = AuthorSchema() | |
book_schema = BookSchema() | |
author = Author(name='Chuck Paluhniuk') | |
# person = Person(name='Chuck Paluhniuk') | |
session.add(author) | |
# session.add(person) | |
book = Book(name='SomeBook', author=author) | |
session.add(book) | |
session.commit() | |
data_dump = author_schema.dump(author).data | |
print data_dump | |
data_dump = person_schema.dump(author).data | |
print data_dump | |
# data, error = author_schema.load(data_dump) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment