SQLAlchemy: Delete object directly from one-to-many relationship without using session.delete() SQLAlchemy: Delete object directly from one-to-many relationship without using session.delete() mysql mysql

SQLAlchemy: Delete object directly from one-to-many relationship without using session.delete()


Read Configuring delete/delete-orphan Cascade section of documentation for more information, but basically you need delete-orphan as well in your cascade option of the relationship:

class Post(Base):    # ...    comments = relationship('Comment', cascade="all, delete-orphan")


I am not a SQLAlchemy user, but I think you should use the ondelete option

    post_id = Column(Integer, ForeignKey(Post.id, ondelete="CASCADE"), nullable=False)

See, Mysql 5.6 Manual 13.6.44, FOREIGN KEY Constraints

SET NULL: Delete or update the row from the parent table, and set the foreign key column or columns in the child table to NULL.Both ON DELETE SET NULL and ON UPDATE SET NULL clauses are supported.
CASCADE: Delete or update the row from the parent table, and automatically delete or update the matching rows in the child table.Both ON DELETE CASCADE and ON UPDATE CASCADE are supported. Between two tables, do not define several ON UPDATECASCADE clauses that act on the same column in the parent table or in the child table.

Andhttp://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html Section: Defining Foreign Keys -> ON UPDATE and ON DELETE