![](/img/trans.png)
[英]SQLAlchemy table with 2 primary_keys how to autoincrement the first primary key
[英]SqlAlchemy table inheritance and primary keys
我在SqlAlchemy中有一个继承的表,抱怨没有主键。 奇怪的是,父表有一个主键。 情况如下:
Parent(Base)
__tablename__= 'parents'
id = Column(INT, primary_key=True, autoincrement=True)
Child(Parent)
__tablename__= 'children'
birthday = Column(TIMESTAMP)
parentId = Column(INT, ForeignKey('parents.uid', onupdate="CASCADE", ondelete="CASCADE"))
parent = relationship("User", backref=backref('CommandsQueued'))
请注意,父表有一个主键,而子表是在继承它。 尽管进行了此设置,但出现以下错误:
SAWarning: Could not assemble any primary keys for locally mapped table 'children' - no rows will be persisted in this Table.
self._configure_pks()
我不明白为什么SA无法识别该表确实具有主键。 有人知道这是怎么回事吗? 我是否误解了SA的继承行为?
我想这只是一个最小的例子,Child作为Parent的子类并没有多大意义。 我希望它们都是Person的子类,或者类似的东西。 在这种情况下,您可能也想看看多态身份。
无论如何,SQLAlchemy继承不是那样工作的。 用您声明的方式,它希望您的Child
类和表声明其自己的主键,因为它是一个单独的表,但是如果尝试使用相同的属性名来进行操作,则会发生冲突。 尝试使用sqlalchemy.orm.column_property
声明基本id列,它应该完成您期望的操作。
因此,对孩子执行以下操作:
id = sqlalchemy.orm.column_property(Column(INT, primary_key=True), Parent.id)
它应该可以按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.