Creating self-referential tables with polymorphism in SQLALchemy
- by Jace
I'm trying to create a db structure in which I have many types of content entities, of which one, a Comment, can be attached to any other.
Consider the following:
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy import Column, ForeignKey
from sqlalchemy import Unicode, Integer, DateTime
from sqlalchemy.orm import relation, backref
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Entity(Base):
__tablename__ = 'entities'
id = Column(Integer, primary_key=True)
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
edited_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
type = Column(Unicode(20), nullable=False)
__mapper_args__ = {'polymorphic_on': type}
# <...insert some models based on Entity...>
class Comment(Entity):
__tablename__ = 'comments'
__mapper_args__ = {'polymorphic_identity': u'comment'}
id = Column(None, ForeignKey('entities.id'), primary_key=True)
_idref = relation(Entity, foreign_keys=id, primaryjoin=id == Entity.id)
attached_to_id = Column(Integer, ForeignKey('entities.id'), nullable=False)
#attached_to = relation(Entity, remote_side=[Entity.id])
attached_to = relation(Entity, foreign_keys=attached_to_id,
primaryjoin=attached_to_id == Entity.id,
backref=backref('comments', cascade="all, delete-orphan"))
text = Column(Unicode(255), nullable=False)
engine = create_engine('sqlite://', echo=True)
Base.metadata.bind = engine
Base.metadata.create_all(engine)
This seems about right, except SQLAlchemy doesn't like having two foreign keys pointing to the same parent. It says ArgumentError: Can't determine join between 'entities' and 'comments'; tables have more than one foreign key constraint relationship between them. Please specify the 'onclause' of this join explicitly.
How do I specify onclause?