Created
July 20, 2015 13:15
-
-
Save lov3catch/cd185d9658980e68c915 to your computer and use it in GitHub Desktop.
psql sqlalchemy cascade delete
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 | |
from sqlalchemy import schema | |
from sqlalchemy import types | |
from sqlalchemy.orm import relationship | |
from sqlalchemy.orm import sessionmaker | |
from sqlalchemy.ext.declarative import declarative_base | |
metadata = schema.MetaData() | |
BaseObject = declarative_base(metadata=metadata) | |
class ParentNew(BaseObject): | |
__tablename__ = 'parent' | |
id = schema.Column(types.Integer(), primary_key=True, autoincrement=True) | |
children = relationship('Child', cascade='all,delete-orphan', passive_deletes=True) | |
class Child(BaseObject): | |
__tablename__ = 'child' | |
id = schema.Column(types.Integer(), primary_key=True, autoincrement=True) | |
parent_id = schema.Column(types.Integer, schema.ForeignKey('parent.id', ondelete='CASCADE'), nullable=False) | |
engine = sqlalchemy.create_engine('postgresql:///pytest', echo=True) | |
metadata.create_all(engine) | |
Session = sessionmaker(bind=engine) | |
session = Session() | |
parent = ParentNew() | |
child = Child() | |
print '-'*50 + '{0}'.format('after creating') | |
print parent.children | |
print '-'*50 | |
session.add(parent) | |
parent.children.append(child) | |
session.commit() | |
print '-'*50 + '{0}'.format('after adding') | |
print parent.children | |
print '-'*50 | |
session.flush() | |
session.delete(child) | |
session.flush() | |
print '-'*50 + '{0}'.format('after deleting NO commit') | |
print parent.children | |
print '-'*50 | |
session.commit() | |
print '-'*50 + '{0}'.format('after deleting YES commit') | |
print parent.children | |
print '-'*50 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment