How to Fix Python SQLAlchemy Relationship Loading Error
In this tutorial, you'll learn about How to Fix Python SQLAlchemy Relationship Loading Error. We cover key concepts, practical examples, and best practices.
SQLAlchemy raises DetachedInstanceError or returns None when a relationship is accessed after the session is closed, or the foreign key is not properly configured.
The Wrong Way
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base, relationship, Session
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
posts = relationship('Post')
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
user_id = Column(Integer) # missing ForeignKey
engine = create_engine('sqlite://')
Base.metadata.create_all(engine)
with Session(engine) as session:
user = session.get(User, 1)
print(user.posts)
Output:
DetachedInstanceError: Parent instance <User at ...> is not bound to a Session
The Right Way
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base, relationship, Session
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
posts = relationship('Post', back_populates='user')
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship('User', back_populates='posts')
engine = create_engine('sqlite://')
Base.metadata.create_all(engine)
with Session(engine) as session:
user = session.get(User, 1)
posts = session.query(Post).filter(Post.user_id == user.id).all()
print(posts)
Output:
[]
Prevention Tips
- Always define
ForeignKeyon the referencing column. - Use
back_populatesto create bidirectional relationships. - Access relationships within an open session.
- Use
joinedload()orselectinload()for eager loading. - Use
lazy='selectin'to avoid N+1 queries.
Common Mistakes with sqlalchemy relationships
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro