Please tell me what I’m doing wrong.
There is this code. Tables are created, model tables
are filled, everything works. But records are not added to the association table.
The code completes without errors, but the drugs_diseases table is empty.
models.py
# Association table
drugs_diseases = Table(
"drugs_diseases",
Base.metadata,
Column("drug_id", ForeignKey("drugs.id"), primary_key=True),
Column("disease_id", ForeignKey("diseases.id"), primary_key=True),
)
class Disease(Base):
__tablename__ = "diseases"
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
drugs = relationship("Drug", secondary=drugs_diseases, back_populates="diseases")
class Drug(Base):
__tablename__ = "drugs"
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
diseases = relationship("Disease", secondary=drugs_diseases, back_populates="drugs")
orm_query.py
async def orm_get_drug(
async_session: async_sessionmaker[AsyncSession], name: str
) -> Drug:
async with async_session() as session:
query = select(Drug).where(Drug.name == name)
drug = await session.scalar(query)
await session.refresh(drug, attribute_names=["diseases"])
return drug
async def orm_get_disease(
async_session: async_sessionmaker[AsyncSession], name: str
) -> Disease:
async with async_session() as session:
query = select(Disease).where(Disease.name == name)
disease = await session.scalar(query)
await session.refresh(disease, attribute_names=["drugs"])
return disease
async def orm_add_drug_disease(
async_session: async_sessionmaker[AsyncSession], name_drug: str, name_disease
) -> None:
async with async_session() as session:
drug = await orm_get_drug(async_session, name_drug)
disease = await orm_get_disease(async_session, name_disease)
drug.diseases.append(disease)
await session.commit()
I’m trying to add an entry to the association table. The code completes without errors, but the entry is not added to the association table.
main.py
...
# "Analgin" is already in the Drug table and "Toothache" is in Disease
await orm_add_drug_disease(session_maker, "Analgin", "Toothache")
if __name__ == "__main__":
asyncio.run(main())
armpomor is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.