Creating self-referential tables with polymorphism in SQLALchemy

Posted by Jace on Stack Overflow See other posts from Stack Overflow or by Jace
Published on 2010-05-19T06:31:09Z Indexed on 2010/05/19 6:50 UTC
Read the original article Hit count: 286

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about python

Related posts about sqlalchemy