簡體   English   中英

在SQLALchemy中創建具有多態性的自引用表

[英]Creating self-referential tables with polymorphism in SQLALchemy

我正在嘗試創建一個數據庫結構,其中我有許多類型的內容實體,其中一個,一個注釋,可以附加到任何其他實體。

考慮以下:

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)

這似乎是正確的,除了SQLAlchemy不喜歡有兩個外鍵指向同一個父。 它說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. 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.

我如何指定onclause

嘗試補充你的Comment.__mapper_args__到:

__mapper_args__ = {
    'polymorphic_identity': 'comment',
    'inherit_condition': (id == Entity.id),
}

PS我還不明白你需要什么_idref關系? 如果你想在某個預期Entity位置使用注釋,你可以按原樣傳遞Comment實例。

補充@ nailxx的答案:如果你有許多依賴表,重復所有樣板是很乏味的。 解決方案:將其全部移至元類。

class EntityMeta(type(Entity)):
    def __init__(cls, name, bases, dct):
        ident = dct.get('_identity',None)
        if '__abstract__' not in dct:
            xid = Column(None, ForeignKey(Entity.id), primary_key=True)
            setattr(cls,'id',xid)
            setattr(cls,'__mapper_args__', { 'polymorphic_identity': dct['_identity'], 'inherit_condition': (xid == Entity.id,), 'primary_key':(xid,) })
            setattr(cls,'__tablename__',name.lower())
        super(EntityMeta, cls).__init__(name, bases, dct)

class EntityRef(Entity):
    __abstract__ = True
    __metaclass__ = EntityMeta

class Comment(EntityRef):
    _identity = 'comment'
    [...]

變體,作為讀者的練習:您可以省略_identity=…語句並使用類名,如setattr(cls,'__tablename__',…)行。 或者不覆蓋現有的__tablename__或__mapper_args__屬性。

一定要測試dct而不是cls是否存在:后者會在父類中找到屬性,這顯然是你現在不想要的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM