SQLalchemy with multiple object hierarchy

本小妞迷上赌 提交于 2019-12-01 00:44:26

Thanks to van and using Inheritance, here is my solution if it could help anyone else:

from sqlalchemy import (
    Column,
    Integer,
    Text,
    ForeignKey,
)

from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    relationship,
    backref,
)

import uuid
from sqlalchemy.ext.declarative import declarative_base
from zope.sqlalchemy import ZopeTransactionExtension

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()

class Node(Base):
    """
    An object representing a node in the hierarchy.
    All the other objects inherit from Node.
    """

    def getID():
        return uuid.uuid1().hex

    __tablename__ = 'Node'
    ID = Column(Text, primary_key=True, default=getID)
    ParentID = Column(Text, ForeignKey('Node.ID'))
    type = Column(Text(50))

    Children = relationship("Node",
                backref=backref('Parent', remote_side=[ID], uselist=False)
            )

    __mapper_args__ = {
        'polymorphic_identity':'Node',
        'polymorphic_on':type
    }


 class A(Node):
    __tablename__ = 'A'
    ID = Column(Text, ForeignKey('Node.ID'), primary_key=True)

    __mapper_args__ = {
        'polymorphic_identity':'A',
    }

class B(Node):
    __tablename__ = 'B'
    ID = Column(Text, ForeignKey('Node.ID'), primary_key=True)

    __mapper_args__ = {
        'polymorphic_identity':'B',
    }

class C(Node):
    __tablename__ = 'C'
    ID = Column(Text, ForeignKey('Node.ID'), primary_key=True)

    __mapper_args__ = {
        'polymorphic_identity':'C',
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!