如何声明包含多列主键的表类? [英] How to declare a table class that contains multi-column primary key?
本文介绍了如何声明包含多列主键的表类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
主键的列必须按特定顺序排列.
The columns of the primary key must be in specific order.
我从文档中看到一些代码:
I see some code from document :
class User(Base):
__tablename__ = 'users'
id = Column(Integer)
__mapper_args__ = {
'primary_key':[id]
}
但是就是不行(我用的是mysql,不会生成id主键).任何可能的解决方案?
But it just does not work (I'm using mysql, and the id primary key will not be generated). Any possible solutions?
推荐答案
如果列的声明顺序与它们在主键中的顺序相同:
In case columns are declared in the same order as they should be in the primary key:
class User(Base):
field1 = Column(Integer, primary_key=True)
field2 = Column(Integer, primary_key=True)
否则在__table_args__
中声明:
class User(Base):
field1 = Column(Integer)
field2 = Column(Integer)
__table_args__ = (
PrimaryKeyConstraint(field2, field1),
{},
)
这篇关于如何声明包含多列主键的表类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文