我正在尝试创建一个db结构,其中我有许多类型的内容实体,其中一个是Comment,可以附加到任何其他内容实体。
请考虑以下事项:
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.
如何指定onclause
?
答案 0 :(得分:10)
尝试将Comment.__mapper_args__
补充到:
__mapper_args__ = {
'polymorphic_identity': 'comment',
'inherit_condition': (id == Entity.id),
}
P.S。我不明白你需要什么_idref
关系?如果您想在Entity
预期的地方使用评论,您可以按原样传递Comment
个实例。
答案 1 :(得分:3)
补充@ 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
是否存在:后者会在父类中找到属性,此时您显然不想要这些属性。