簡體   English   中英

SQLAlchemy:創建由另一個復合主鍵組成的復合主鍵

[英]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  |             └───────┘            └───────┘
└────────┘

一個人可以有多個寵物,一個寵物可以有多個玩具。 到目前為止,這很簡單。

更難的部分是我希望PetToy具有復合主鍵:

  • 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM