ΠΠ΅Π±-ΡΠ°Π·ΡΠ°Π±ΠΎΡΠΊΠ°. ΠΠΎΠΌΠΎΡΡ Π² ΠΊΠΎΠ½ΠΊΡΠ΅ΡΠ½ΠΎΠΌ Π²ΠΎΠΏΡΠΎΡΠ΅. ΠΠΈΡΡ ΠΏΡΠΎΠ΅ΠΊΡ Π½Π° FastAPI, Π΅ΡΡΡ ΠΎΠ΄ΠΈΠ½ Π²ΠΎΠΏΡΠΎΡ ΠΏΠΎ ΡΠΎΠ·Π΄Π°Π½ΠΈΡ ΡΠΌΠ΅ΠΆΠ½Π°Ρ ΡΠ°Π±Π»ΠΈΡΠ° Π΄Π»Ρ ΡΠ²ΡΠ·ΠΈ M to M: --------------------------------------- |Subject_user_association| -------------------------------------- | FK | user_id | -------------------------------------- | FK | subject_name | ΠΏΠΎΡΠΊΠΎΠ»ΡΠΊΡ ΠΏΠΎΠ»Ρ user_id, subject_name , ΡΠ²Π»ΡΡΡΡΡ FK ΠΈ Π΄Π»Ρ Π΄ΡΡΠ³ΠΈΡ
ΡΠ°Π±Π»ΠΈΡ, ΡΠ΅ΡΠΈΠ» Π½Π°ΠΏΠΈΡΠ°ΡΡ Π±Π°Π·ΠΎΠ²ΡΠΉ mixin, Π΄Π»Ρ ΠΎΠΏΡΠ΅Π΄Π΅Π»Π΅Π½ΠΈΡ FK, Π° ΠΏΠΎΡΠΎΠΌ ΡΠ΄Π΅Π»Π°ΡΡ Π΄Π²Π° Π½Π°ΡΠ»Π΅Π΄Π½ΠΈΠΊΠ° Π΄Π»Ρ ΡΠΎΠ·Π΄Π°Π½ΠΈΡ FK user_id ΠΈ FK subject_name, ΠΏΠΎΠ»ΡΡΠΈΠ»ΠΎΡΡ ΡΠ»Π΅Π΄ΡΡΡΠΈΠ΅: class BaseMixin: _back_populates: str | None = None _field_fk: str = 'id' _table_name: [Email ΡΠΊΡΡΡ] def _create_fk(cls)-> Mapped[int | str]: return mapped_column(ForeignKey(f'{cls._table_name}.{cls._field_fk}'))@classmethod def _create_relationship(cls): return relationship( f“{cls.__name__}“, back_populates=cls._back_populates, ) class UserRelationMixin(BaseMixin): _table_name = 'user' @declared_attr def user_id(cls) -> Mapped[int]: return cls._create_fk() @declared_attr def user(cls) -> Mapped['User']: return cls._create_relationship() class SubjectRelationMixin(BaseMixin): _table_name = 'subject' _field_fk = 'name' @declared_attr def subject_name(cls) -> Mapped[str]: return cls._create_fk() @declared_attr def subject(cls) -> Mapped[“Subject“]: return cls._create_relationship() Π½ΠΎ ΠΏΡΠΈ ΡΠΎΠ·Π΄Π°Π½ΠΈΠΈ ΡΠ°Π±Π»ΠΈΡΡ: class SubjectUserAssociation( SubjectRelationMixin, UserRelationMixin, Base, ): pass Π‘ΠΎΠ·Π΄Π°Π΅ΡΡΡ ΡΠ»Π΅Π΄ΡΡΡΠ΅Π΅: sa.ForeignKeyConstraint(['subject_name'], ['subject.name'], ), sa.ForeignKeyConstraint(['user_id'], ['subject.name'], ), Π Ρ
ΠΎΡΡ ΡΠ΅Π°Π»ΠΈΠ·ΠΎΠ²Π°ΡΡ ΡΠ»Π΅Π΄ΡΡΡΠΈΠ΅: sa.ForeignKeyConstraint(['subject_name'], ['subject.name'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), Π― ΠΏΠΎΠ½ΠΈΠΌΠ°Ρ ΠΏΠΎΡΠ΅ΠΌΡ ΡΡΠΎ ΠΏΡΠΎΠΈΡΡ
ΠΎΠ΄ΠΈΡ, Π½ΠΎ Π½Π΅ ΠΌΠΎΠ³Ρ ΠΏΡΠΈΠ΄ΡΠΌΠ°ΡΡ ΠΊΠ°ΠΊ ΡΠ΅Π°Π»ΠΈΠ·ΠΎΠ²Π°ΡΡ Π·Π°Π΄ΡΠΌΠ°Π½Π½ΡΠΉ ΡΠ΅Π·ΡΠ»ΡΡΠ°Ρ.