Skip to content

Instantly share code, notes, and snippets.

@rdarder
Created February 19, 2015 14:33
Show Gist options
  • Save rdarder/667610253e2747a5bf8b to your computer and use it in GitHub Desktop.
Save rdarder/667610253e2747a5bf8b to your computer and use it in GitHub Desktop.
Self reference foreign key example. Test to check if mysql and sqlite supported DEFERRED constraint checks, turns out not.
from sqlalchemy import Column, Integer, ForeignKey, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, Session
Base = declarative_base()
class Person(Base):
__tablename__ = 'persons'
id = Column(Integer, primary_key=True)
best_friend_id = Column(
Integer,
ForeignKey('persons.id', use_alter=True, name='fk_best_friend'))
#if we wanted to set nullable=False to the foreignkey, we'd need an engine with
# DEFERRED constraing checks support
best_friend = relationship(
'Person',
primaryjoin='Person.best_friend_id==Person.id',
post_update=True,
foreign_keys=[best_friend_id],
uselist=False
)
engine = create_engine('sqlite:///')
session = Session(bind=engine)
Base.metadata.create_all(bind=engine)
guy1 = Person()
guy1.best_friend = guy1
session.add(guy1)
session.commit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment