0

I have two tables, DataBaseFirst and DataBaseSecond. I am maintaining a connection between two tables on a column session_id. What I want is that when i delete client_id in first table, the corresponding rows in table 2 should also be deleted.

class DataBaseFirst(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    session_id: str
    client_id: str
    field1 : str
    field2 : str

class DataBaseSecond(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    session_id: str = Field(foreign_key="databasefirst.session_id")
    field3 : str
    field4 : str

How Can I do that? I tried this

 with Session(engine) as session:
    statement = f"DELETE FROM databasefirst WHERE client_id = '{client_id}'"
    session.exec(statement)
    # Commit the changes
    session.commit()

But it delete the rows from first table only, not the connected rows from second table

Talha Anwar
  • 2,699
  • 4
  • 23
  • 62
  • Shouldn't `session_id` on `DataBaseFirst` at least have a `UNIQUE` constraint to be referenced by a foreign key? Also, why not just link the two via the primary key `databasefirst.id`? – Daniil Fajnberg Feb 20 '23 at 22:21

0 Answers0