有两个具有预定义名称的имя_класса.lower()+'s'
表id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
无法在两个表之间以及第一个表的记录之间创建多对多关系。
“构建”表:
class Assembly(Base):
serial_number: Mapped[str_uniq] = mapped_column(String)
name: Mapped[str] = mapped_column(String)
link: Mapped[str] = mapped_column(String)
deleted_at: Mapped[DateTime] = mapped_column(DateTime)
# Связь с таблицей assemblyparts через backref
parts: Mapped[list['Part']] = relationship(
'Part',
secondary='assemblyparts',
back_populates='assemblys'
)
# Связь с другими сборками через backref
child_assemblys: Mapped[list['Assembly']] = relationship(
'Assembly',
secondary='assemblycompositions',
primaryjoin=id == column('parent_assembly_id'),
secondaryjoin=id == column('child_assembly_id'),
back_populates='parent_assemblys'
)
parent_assemblys: Mapped[list['Assembly']] = relationship(
'Assembly',
secondary='assemblycompositions',
primaryjoin=id == column('child_assembly_id'),
secondaryjoin=id == column('parent_assembly_id'),
back_populates='child_assemblys'
)
和“详细信息”:
class Part(Base):
serial_number: Mapped[str_uniq] = mapped_column(String)
name: Mapped[str] = mapped_column(String)
link: Mapped[str] = mapped_column(String)
deleted_at: Mapped[DateTime] = mapped_column(DateTime)
# Связь с таблицей assembly_parts через backref
assemblys: Mapped[list['Assembly']] = relationship(
'Assembly',
secondary='assemblyparts',
back_populates='parts'
)
还有关联表:
class AssemblyPart(Base):
'''Ассоциативная таблица для связей между сборками и деталями'''
assembly_id: Mapped[int] = mapped_column(ForeignKey('assemblys.id'), primary_key=True)
part_id: Mapped[int] = mapped_column(ForeignKey('parts.id'), primary_key=True)
quantity: Mapped[int] = mapped_column(Integer)
class AssemblyComposition(Base):
'''Промежуточная таблица для связи many-to-many между сборками'''
parent_assembly_id: Mapped[int] = mapped_column(ForeignKey('assemblys.id'))
child_assembly_id: Mapped[int] = mapped_column(ForeignKey('assemblys.id'))
quantity: Mapped[int] = mapped_column(Integer)
# Составной первичный ключ
__table_args__ = (
PrimaryKeyConstraint('parent_assembly_id', 'child_assembly_id'),
)
对于装配和零件之间的多对多关系,使用AssemblyPart表- 每个零件可以是多个装配的一部分,并且每个装配可以包含多个零件。另外,每个组件可以包括其他组件并且其本身可以包括在其他组件中。
初始化表的时候出现错误:
sqlalchemy.exc.ArgumentError:无法在关系 Assembly.child_assembles 上找到主联接条件“parent_ assembly_id = :parent_ assembly_id_1”的任何相关外键列。
确保引用列与ForeignKey 或ForeignKeyConstraint 关联,或者在连接条件中使用foreign() 注释进行注释。
如果删除用于将程序集相互连接的关联表 ( AssemblyComposition ) 并从Assembly中删除它的参数,则表的初始化可以正常工作。那些。正确定义了零件和装配体之间的关系。
我做错了什么?