I have two tables and need create many to many table : class CustomerObject(Base):…
- User
I have two tables and need create many to many table : class CustomerObject(Base): tablename = 'customer_obj'
name: Mapped[str] = mapped_column(VARCHAR(100), unique=True, nullable=False) address: Mapped[str] = mapped_column(VARCHAR(100), nullable=False) phone_numbers: Mapped[str] = mapped_column(VARCHAR(100), nullable=False) schedule: Mapped[list] = mapped_column(ARRAY( [[Column('opentime', TIME(timezone=True)), Column('closetime', TIME(timezone=True)), Column('worktime', BIGINT)] for _ in range(7)], dimensions=2)) area_int: Mapped[int] = mapped_column(INTEGER, nullable=False) trade_area_int: Mapped[int] = mapped_column(INTEGER, nullable=False) slab_height_int: Mapped[int] = mapped_column(SMALLINT, nullable=False) ceiling_height_int: Mapped[int] = mapped_column(SMALLINT, nullable=False) service_end_date: Mapped[date | None] = mapped_column(DATE, default=None) city_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('city.id'), nullable=False) ceiling_type_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('ceiling_type.id'), nullable=False) city: Mapped["City"] = relationship(lazy='subquery') ceiling_type: Mapped["CeilingType"] = relationship(lazy='subquery') class Customer(Base): __tablename__ = 'customer' name: Mapped[str] = mapped_column(VARCHAR(32), unique=True, nullable=False) noservice_date: Mapped[date | None] = mapped_column(DATE, default=None) - Assistant
- User
what means secondary=‘customer_customer_obj’
- Assistant
In SQLAlchemy, the
secondaryattribute is used to define the association table in a many-to-many relationship. In this case, thesecondary='customer_customer_obj'argument is used to specify that theCustomerObjectandCustomerclasses are linked through thecustomer_customer_objassociation table.More specifically, the
secondaryattribute is used to specify the name of the association table to be used to link the two tables together. In this case, thecustomer_customer_objtable is used to connectCustomerobjects toCustomerObjectobjects.By defining the association table using
secondary, SQLAlchemy can automatically generate the necessary SQL for joining the two tables together in a many-to-many relationship. This makes it much easier to work with many-to-many relationships in SQLAlchemy, since you don't have to manually write the SQL statements to connect the two tables together.