![](/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.