title: SQLAlchemy - Dependency rule tries to blank-out primary key column of deleted object
body: <p>Here is an example code that demonstrates my problem:</p>
  
  <pre><code>from sqlalchemy import Column, create_engine, Integer
  from sqlalchemy.orm import sessionmaker, relationship, backref
  from sqlalchemy.ext.declarative import declarative_base
  from sqlalchemy import event, ForeignKey, and_
  
  Base = declarative_base()
  
  class A(Base):
      __tablename__ = 'as'
      aid = Column(Integer, primary_key=True)
  
  class F(Base):
      __tablename__ = 'fs'
      fid = Column(Integer, primary_key=True)
  
  class G(Base):
      __tablename__ = 'gs'
      aid = Column(Integer, ForeignKey('as.aid'), primary_key=True)
      fid = Column(Integer, ForeignKey('fs.fid'), primary_key=True)
      a = relationship('A')
      f = relationship('F')
  
  class X(Base):
      __tablename__ = 'xs'
      aid = Column(Integer, ForeignKey('as.aid'), primary_key=True)
      fid = Column(Integer, ForeignKey('fs.fid'), primary_key=True)
      a = relationship('A')
      f = relationship('F')
      g = relationship('G', primaryjoin="and_(X.aid==G.aid, X.fid==G.fid)", foreign_keys=[aid, fid], backref=backref('active', uselist=False))
  
  e = create_engine("sqlite://", echo=True)
  Base.metadata.create_all(e)
  
  sm = sessionmaker(bind=e, expire_on_commit=False)
  s = sm()
  
  a = A(aid=1)
  s.add(a)
  s.commit()
  
  f = F(fid=1)
  s.add(f)
  s.commit()
  
  g = G()
  g.a = a
  g.f = f
  s.add(g)
  s.commit()
  
  g.active = X()
  g.active.a = a
  g.active.f = f
  s.add(g.active)
  s.commit()
  
  # Goal: delete g.active. under some conditions, delete g.a and g as well
  
  s.delete(g.active)
  s.commit()
  s.delete(g.a)
  s.commit()
  g.active = None
  s.delete(g)
  s.commit()  # Dependency rule tried to blank-out primary key column 'xs.aid' on instance '&lt;X at 0x3f89230&gt;'
  </code></pre>
  
  <p>Question: How can I delete g.a and g, after already deleting g.active, without getting this error? Do I need some kind of cascade?</p>
  
  <p>Please note that I don't always want to delete g.a and g in my real application (it is variable), so I don't want a cascade that will always delete them.</p>