簡體   English   中英

SQLAlchemy:直接從一對多關系中刪除對象,而不使用session.delete()

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

我有以下SQLAlchemy設置:

Base = declarative_base()

class Post(Base):
    __tablename__ = 'post'
    id = Column(Integer, primary_key=True)
    title = Column(String(30))
    comments = relationship('Comment', cascade='all')

class Comment(Base):
    __tablename__ = 'comment'
    id = Column(Integer, primary_key=True)
    post_id = Column(Integer, ForeignKey(Post.id, ondelete='CASCADE'), nullable=False)
    text = Column(Text)

有了這個,我可以用注釋的一對多關系創建post對象。 我想處理創建和刪除帖子的評論而不引用會話。 在帖子中添加評論就可以了:

post = Post(title='some post')
comment = Comment(text='some comment')
post.comments.append(comment)

我的會話處理程序只知道帖子,所以它會執行session.add(post) ,並且注釋會自動放入會話中,並在下一個session.commit()上與數據庫同步。 但是,刪除評論的情況也是如此。 我希望能夠通過以下方式刪除評論:

post.comments.remove(comment)

但是,這會在下一個session.commit()上產生以下錯誤:

sqlalchemy.exc.OperationalError: (OperationalError) (1048, "Column 'post_id' cannot be null") 'UPDATE comment SET post_id=%s WHERE comment.id = %s' (None, 1L)

如何告訴SQLAlchemy不使用post_id的NULL值更新注釋(由於列上的非空約束而不允許),但是刪除注釋? 我知道我可以做session.delete(comment) ,但由於我不需要明確地向會話添加評論,所以我沒有看到為什么我必須明確地從會話中刪除它。

我發現了幾個用於級聯刪除相關對象的解決方案,但由於我從未對會話發出任何明確的刪除(帖子仍在那里),我認為這不適用。

編輯 :我調整了示例以包含帖子中刪除的級聯。 現在它可以做session.delete(post)並刪除所有注釋。 但我只是想自動刪除我從關系中刪除的評論,而不是刪除所有評論的整個帖子。

TL; DR :當我從一對多關系的關系列表中刪除條目時,如何告訴SQLAlchemy發出刪除語句而不是更新語句?

有關詳細信息,請參閱配置刪除/刪除 - 孤立級聯文檔部分,但基本上您還需要在relationship cascade選項中使用delete-orphan

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

我不是SQLAlchemy用戶,但我認為你應該使用ondelete選項

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

參見,Mysql 5.6手冊13.6.44,FOREIGN KEY約束

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 UPDATE
CASCADE clauses that act on the same column in the parent table or in the child table.

http://docs.sqlalchemy.org/en/rel_0_9/core/constraints.html章節:定義外鍵 - > ON UPDATE和ON DELETE

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM