简体   繁体   中英

SQLAlchemy: Adjacency List with Single Table Inheritance

I am trying to setup the following single-table inheritance adjacency list structure, where the child object contains a relationship to the parent object:

class Parent(Base):
    __tablename__ = 'testtable'
    type = Column(String)
    __mapper_args__ = {
        'polymorphic_on':type,
        'polymorphic_identity':'Parent'
    }

    id = Column(Integer, primary_key = True)

class Child(Parent):
    __mapper_args__ = {
        'polymorphic_identity':'Child'
    }

    parent_id = Column(Integer, ForeignKey('testtable.id'))
    parent = relationship('Parent')

However, when I try to create an object, of type Child, and set / append a parent object:

p = Parent()
c = Child()
c.parent.append(p)

db_session.add(c)
db_session.commit()

I get the following error:

UnmappedColumnError: Can't execute sync rule for destination column 'testtable.parent_id'; mapper 'mapped class Parent->testtable' does not map this column. Try using an explicit foreign_keys collection which does not include this column (or use a viewonly=True relation).

I played around with different relationship definitions (backref etc.) but am pretty lost at this stage. Any ideas would be highly appreciated!

Thanks a lot in advance

For convenience, here is a full example:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship

Base = declarative_base()
Session = sessionmaker()

engine = create_engine('sqlite:///test.db')
Session.configure(bind = engine)
db_session = Session()

class Parent(Base):
    __tablename__ = 'testtable'
    type = Column(String)
    __mapper_args__ = {
        'polymorphic_on':type,
        'polymorphic_identity':'Parent'
    }

    id = Column(Integer, primary_key = True)

class Child(Parent):
    __mapper_args__ = {
        'polymorphic_identity':'Child'
    }

    parent_id = Column(Integer, ForeignKey(Parent.id))
    parent = relationship('Parent', remote_side=[parent_id])

Base.metadata.create_all(engine)

p = Parent()
c = Child()
c.parent.append(p)

db_session.add(c)
db_session.commit()

Your Child object has a single foreign key to Parent so it is a many-to-one relationship. Therefore you need to use c.parent = p instead of c.parent.append(p) . You also need to use remote_side=Parent.id to establish the relationship .

Working example:

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import declarative_base, relationship, Session

Base = declarative_base()

engine = create_engine("sqlite://")


class Parent(Base):
    __tablename__ = "testtable"
    type = Column(String)
    __mapper_args__ = {
        "polymorphic_on": type,
        "polymorphic_identity": "Parent",
    }

    id = Column(Integer, primary_key=True)

    def __repr__(self):
        return f"<Parent(id={self.id})>"


class Child(Parent):
    __mapper_args__ = {"polymorphic_identity": "Child"}

    parent_id = Column(Integer, ForeignKey(Parent.id))
    parent = relationship("Parent", remote_side=Parent.id)

    def __repr__(self):
        return f"<Child(id={self.id}, parent_id={self.parent_id})>"


Base.metadata.create_all(engine)

with Session(engine) as db_session:
    p = Parent()
    c = Child()
    c.parent = p
    db_session.add(c)
    db_session.commit()
    print(c)  # <Child(id=2, parent_id=1)>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM