在SQLAlchemy中,如何声明由另一个复合主键组成的复合主键?
假设我有这样的模型:
┌────────┐ ┌───────┐ ┌───────┐
| Person | ── 1,n ──> | Pet | ── 1,n ──> | Toy |
├--------┤ ├-------┤ ├-------┤
| id | | age | | color |
| name | └───────┘ └───────┘
└────────┘一个人可以有多个宠物,一个宠物可以有多个玩具。到目前为止,这很简单。
更难的是,我希望Pet和Toy具有复合主键:
(Person.id, Pet.age)
Person的主键是
Person的主键是
Pet的主键是,的主键,,Toy的主键是(<Pet primary key>, Toy.color)。我挣扎的地方是在Toy的复合主键中使用Toy。
以下是我迄今所做的尝试:
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')发布于 2020-10-07 16:33:18
找到它:
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)https://stackoverflow.com/questions/64246193
复制相似问题