Python SQLAlchemy:创建一个由另一个复合主键组成的复合主键
在SQLAlchemy中,如何声明由另一个复合主键组成的复合主键 假设我有这个模型:Python SQLAlchemy:创建一个由另一个复合主键组成的复合主键,python,sqlalchemy,Python,Sqlalchemy,在SQLAlchemy中,如何声明由另一个复合主键组成的复合主键 假设我有这个模型: ┌────────┐ ┌───────┐ ┌───────┐ | Person | ── 1,n ──> | Pet | ── 1,n ──> | Toy | ├--------┤ ├-------┤ ├-------┤ | id | | age |
┌────────┐ ┌───────┐ ┌───────┐
| Person | ── 1,n ──> | Pet | ── 1,n ──> | Toy |
├--------┤ ├-------┤ ├-------┤
| id | | age | | color |
| name | └───────┘ └───────┘
└────────┘
一个人可以养多只宠物,一只宠物可以养多个玩具。到目前为止,这很简单
更难的是,我希望Pet
和Toy
具有复合主键:
的主键是Person
id
的组合主键是Pet
(Person.id,Pet.age)
玩具的组合主键是
(,Toy.color)
玩具
的复合主键中的
以下是我迄今为止所做的尝试:
class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True, unique=True)
name = Column(String, unique=True, index=True)
class Pet(Base):
__tablename__ = 'pet'
__table_args__ = (PrimaryKeyConstraint('age', 'person_id', name='pet_pk'),)
age = Column(Integer, default=0)
person_id = Column(Integer, ForeignKey('person.id'))
class Toy(Base):
__tablename__ = 'toy'
__table_args__ = (PrimaryKeyConstraint('color', ???, name='toy_pk'),)
color = Column(String)
由于Pet
的主键是一个复合主键,我如何在另一个复合主键中使用它
在我的Toy
表中,我是否应该添加一个pet\u age
列和一个person\u id
列来构建pet
组合键,以便我可以这样引用它:
(PrimaryKeyConstraint('color', 'pet_age', 'person_id', name='toy_pk')
?找到它:
- 我需要声明我的
表中的所有Toy
组合主键Pet
- 使用所有这些字段创建一个新的复合主键
- 并声明具有多个字段的外键约束:
class Toy(Base):
__tablename__ = 'toy'
__table_args__ = (
PrimaryKeyConstraint('color', 'pet_age', 'person_id', name='toy_pk'),
ForeignKeyConstraint(['pet_age', 'person_id'], ['pet.age', 'pet.person_id'])
)
color = Column(String)
pet_age = Column(Integer)
person_id = Column(Integer)