Issue
I have two tables with a many (user_data_relation) to one (data) relationship.
I have been using SQLAlchemy Core and created Table objects for both.
meta = MetaData()
Data = Table(
"data", meta,
Column('id', Integer, primary_key=True, unique=True),
Column('data_id', String(100)),
Column('text', String(25000)),
Column('created_at', DateTime(timezone=True)),
)
User_Data_Relation = Table(
"user_data_relation", meta,
Column('id', Integer, primary_key=True),
Column('data_id', Integer, ForeignKey('data.id')),
)
meta.create_all(engine)
I am unable to delete a row from data now, since there is a ForeignKey constraint in the user_data_relation table.
I am trying to implement Cascading deletes, but the documentation only shows how to do it for ORM: https://docs.sqlalchemy.org/en/14/orm/cascades.html#delete
Any ideas how to do this using Table objects and SQLAlchemy Core?
Solution
Pretty much the same as for ORM, you can specify ondelete argument on ForeignKey. If you want cascade deleting use:
ForeignKey('data.id', ondelete='CASCADE'))
For your example, this query will be generated:
CREATE TABLE user_data_relation (
id INTEGER NOT NULL,
data_id INTEGER,
PRIMARY KEY (id),
FOREIGN KEY(data_id) REFERENCES data (id) ON DELETE CASCADE
)
Answered By - funnydman Answer Checked By - Willingham (sql.easybugfix Volunteer)
Post a Comment
Post a Comment