Last active
August 27, 2015 19:15
-
-
Save dpwrussell/c74c8ad628cc28d8bc56 to your computer and use it in GitHub Desktop.
MarshmallowSqlalchemy issue with one/many to zero/one using sqlalchemy's uselist=False
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 Author(Base): | |
__tablename__ = 'authors' | |
id = sa.Column(sa.Integer, primary_key=True) | |
name = sa.Column(sa.String) | |
featuring = relationship('FeaturedAuthor', uselist=False, | |
backref='author') | |
@hybrid_property | |
def featured(self): | |
if self.featuring is not None: | |
return True | |
return False | |
@featured.expression | |
def featured(cls): | |
if cls.featuring is not None: | |
return True | |
return False | |
def __repr__(self): | |
return '<Author(name={self.name!r})>'.format(self=self) | |
class FeaturedAuthor(Base): | |
__tablename__ = 'featuredauthors' | |
id = sa.Column(sa.Integer, sa.ForeignKey('authors.id'), primary_key=True) | |
Base.metadata.create_all(engine) | |
class AuthorSchema(ModelSchema): | |
class Meta: | |
model = Author | |
sqla_session = session | |
author_schema = AuthorSchema() | |
author = Author(name='Chuck Paluhniuk') | |
# featured_author = FeaturedAuthor(author=author) | |
session.add(author) | |
# session.add(featured_author) | |
session.commit() | |
print 'Featured:', author.featured | |
data_dump = author_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