Created
July 13, 2018 04:42
-
-
Save funseiki/72c8b8cdd5e39b97385ce638de887fa1 to your computer and use it in GitHub Desktop.
SqlAlchemy AttributeError for Unmapped Subclasses
This file contains hidden or 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 import * | |
from sqlalchemy.orm import * | |
from sqlalchemy.ext.associationproxy import association_proxy | |
metadata = MetaData() | |
fruitTypesTable = Table( | |
'FruitTypes', metadata, | |
Column('type_id', Integer, primary_key=True), | |
Column('name', String(256)) | |
) | |
fruitsTable = Table( | |
'Fruits', metadata, | |
Column('fruit_id', Integer, primary_key=True), | |
Column('type_id', Integer, ForeignKey(fruitTypesTable.c.type_id)), | |
Column('name', String(256)), | |
Column('sweetness', Integer) | |
) | |
applesTable = Table( | |
'Apples', metadata, | |
Column('fruit_id', Integer, ForeignKey(fruitsTable.c.fruit_id), primary_key=True), | |
Column('appleyness', Integer) | |
) | |
class FruitType(object): | |
def __init__(self, *args, **kwds): | |
for key in kwds: | |
setattr(self, key, kwds[key]) | |
pass | |
return | |
def __repr__(self): | |
return "{}<{}>".format(self.__class__.__name__, self.__dict__) | |
class Fruit(object): | |
def __init__(self, *args, **kwds): | |
for key in kwds: | |
setattr(self, key, kwds[key]) | |
pass | |
return | |
def __repr__(self): | |
return "{}<{}>".format(self.__class__.__name__, self.__dict__) | |
class Apple(Fruit): pass | |
class GrannySmith(Fruit): pass | |
class Rotten(Apple): pass | |
engine = create_engine('sqlite://') | |
metadata.create_all(engine) | |
Session = sessionmaker(bind=engine) | |
session = Session() | |
mapper(FruitType, fruitTypesTable) | |
appleType = FruitType(id=1, name='apple') | |
grannySmithType = FruitType(id=2, name='grannysmith') | |
session.add(appleType) | |
session.commit() | |
mapper(Fruit, fruitsTable, | |
polymorphic_on="type_id", | |
properties={ | |
"typeObject": relationship(FruitType) | |
}) | |
Fruit.fruitType = association_proxy("typeObject", 'name') | |
mapper(Apple, applesTable, | |
inherits=Fruit, | |
polymorphic_identity=1) | |
mapper(GrannySmith, applesTable, | |
inherits=Fruit, | |
polymorphic_identity=2) | |
r = Rotten(appleyness=0) # Error here |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment