Last active
August 29, 2015 14:06
-
-
Save ods/1d49921a72189b573900 to your computer and use it in GitHub Desktop.
Bug in SQLAlchemy: None assigned to relationship is not stored to DB
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
from sqlalchemy import Column, Integer, String, ForeignKey, create_engine | |
from sqlalchemy.orm import relationship, sessionmaker | |
from sqlalchemy.ext.declarative import declarative_base | |
Base = declarative_base() | |
class DocLink(Base): | |
__tablename__ = 'DocLink' | |
id = Column(Integer, primary_key=True) | |
block_id = Column(ForeignKey('DocLinkBlock.id', ondelete='CASCADE'), | |
nullable=False) | |
block = relationship('DocLinkBlock', | |
primaryjoin='DocLink.block_id==DocLinkBlock.id') | |
ref_url = Column(String(250), nullable=True) | |
ref_doc_id = Column(ForeignKey('Doc.id')) | |
ref_doc = relationship('Doc', primaryjoin='DocLink.ref_doc_id==Doc.id') | |
class DocLinkBlock(Base): | |
__tablename__ = 'DocLinkBlock' | |
id = Column(Integer, primary_key=True) | |
doc_id = Column(ForeignKey('Doc.id', ondelete='CASCADE'), nullable=False) | |
doc = relationship('Doc') | |
links = relationship(DocLink, cascade='all, delete-orphan') | |
class Doc(Base): | |
__tablename__ = 'Doc' | |
id = Column(Integer, primary_key=True) | |
link_blocks = relationship(DocLinkBlock, cascade='all, delete-orphan') | |
engine = create_engine('sqlite://', echo=True) | |
Base.metadata.create_all(engine) | |
session = sessionmaker(bind=engine)() | |
ref_doc = Doc(id=1) | |
session.add(ref_doc) | |
session.commit() | |
doc = Doc( | |
id=2, | |
link_blocks=[ | |
DocLinkBlock( | |
id=1, | |
links=[ | |
DocLink( | |
id=1, | |
ref_url='url', | |
ref_doc=ref_doc, | |
), | |
], | |
), | |
], | |
) | |
session.add(doc) | |
session.commit() | |
assert doc.link_blocks[0].links[0].ref_url=='url' | |
assert doc.link_blocks[0].links[0].ref_doc is ref_doc | |
doc.link_blocks = [ | |
DocLinkBlock( | |
id=1, | |
links=[ | |
DocLink( | |
id=1, | |
ref_url=None, | |
ref_doc=None, | |
), | |
], | |
), | |
] | |
session.commit() | |
assert doc.link_blocks[0].links[0].ref_url is None | |
assert doc.link_blocks[0].links[0].ref_doc is None # Fails |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment