![](/img/trans.png)
[英]Generic way to get primary key from declaratively defined instance in SQLAlchemy
[英]SQLAlchemy: Possible to declare a column as primary key declaratively?
我有一个基类mixin:
class MyColumns(object):
id = Column(Integer)
foo = Column(Integer)
bar = Column(Integer)
class MyMainTable(MyColumns, Base):
__tablename__ = 'main_table'
pk_id = PrimaryKeyConstraint("id")
我希望能够将id
声明为MyMainTable上的PK。 我无法在MyColumns
其声明为PK,因为我需要在另一个表中使用MyColumns
,其中id不是PK(出于审计目的而做)。 当我运行上面的代码时,我得到
sqlalchemy.exc.ArgumentError: Mapper Mapper|MyMainTable|main_table could not assemble any primary key columns for mapped table 'main_table'
有什么办法可以这样添加PK声明吗?
我找到了此处记录的解决方案: http : //docs.sqlalchemy.org/en/rel_0_9/core/constraints.html#setting-up-constraints-when-using-the-declarative-orm-extension
您需要将约束添加到__table_args__
:
class MyColumns(object):
id = Column(Integer)
foo = Column(Integer)
bar = Column(Integer)
class MyMainTable(MyColumns, Base):
__tablename__ = 'main_table'
__table_args__ = (
PrimaryKeyConstraint("id", name="pk_id"),
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.