【问题标题】:SQLAlchemy: create a composite primary key made of another composite primary keySQLAlchemy:创建由另一个复合主键组成的复合主键
【发布时间】:2020-10-07 14:27:13
【问题描述】:

在 SQLAlchemy 中,如何声明由另一个复合主键组成的复合主键?

假设我有这个模型:

┌────────┐             ┌───────┐            ┌───────┐
| 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')

?

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    找到了:

    • 我需要在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)
    

    【讨论】:

      猜你喜欢
      • 2017-06-14
      • 2019-03-12
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多