[英]SQLAlchemy: create a composite primary key made of another composite primary key
在 SQLAlchemy 中,如何聲明由另一個復合主鍵構成的復合主鍵?
假設我有這個 model:
┌────────┐ ┌───────┐ ┌───────┐
| Person | ── 1,n ──> | Pet | ── 1,n ──> | Toy |
├--------┤ ├-------┤ ├-------┤
| id | | age | | color |
| name | └───────┘ └───────┘
└────────┘
一個人可以有多個寵物,一個寵物可以有多個玩具。 到目前為止,這很簡單。
更難的部分是我希望Pet
和Toy
具有復合主鍵:
Person
的主鍵是id
Pet
的復合主鍵是(Person.id, Pet.age)
Toy
的組合主鍵是(<Pet primary key>, Toy.color)
我掙扎的地方是在Toy
的復合主鍵中使用<Pet primary key>
。
到目前為止,這是我嘗試過的:
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_age
列和一個person_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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.