python data_error ai_generated true

sqlalchemy.exc.FlushError: Instance <Child at 0x...> has a NULL identity key. If this is an auto-generated value, check that the database table allows generation of new primary key values, and that the mapped Column object is configured correctly.

ID: python/sqlalchemy-relationship-delete-orphan-without-cascade

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2025-01-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Trying to delete a child object that is not properly associated or has missing primary key, often due to missing cascade delete-orphan.

generic

中文

试图删除未正确关联或缺少主键的子对象,通常由于缺少 cascade delete-orphan。

Workarounds

  1. 95% success
    class Parent(Base):
        children = relationship('Child', cascade='all, delete-orphan')
    # Then remove child: parent.children.remove(child)
  2. 80% success
    session.delete(child)
    session.commit()

Dead Ends

Common approaches that don't work:

  1. 50% fail

    May conflict with auto-increment; not scalable.

  2. 70% fail

    The child still exists in session and gets flushed.