On Jun 6, 2011, at 7:13 PM, Geoff wrote:

> On Jun 6, 11:32 pm, Michael Bayer <mike...@zzzcomputing.com> wrote:
>> 
>> The table referenced by "secondary=" in a relationship() is managed 
>> entirely, regardless of cascade setting, but
>> only from the perspective of the parent.  Meaning if A references a 
>> collection of B, the row in a_to_b will be
>> deleted if you 1. delete A, or 2. remove a B from A's collection.   Deleting 
>> a B by itself as in session.delete(B)
>> won't have an effect unless you apply a backref to the relationship so that 
>> each B also knows about its collection
>> of  A.
> 
> I am indeed deleting B but in this case I do have the backref
> specified in the parent table A e.g.
> 
> Class A(Base):
>  toB = relationship('B', secondary=a_b, backref='toA')

Below is a short test, can you figure out what you might be doing differently ?

from sqlalchemy import create_engine, Column, Integer, Table, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session, relationship

Base = declarative_base()

class A(Base):
   __tablename__ = 'a'
   id = Column(Integer, primary_key=True)
   related = relationship("B", 
                secondary=Table(
                        'secondary', 
                        Base.metadata, 
                        Column('aid', Integer, ForeignKey('a.id'), 
primary_key=True), 
                        Column('bid', Integer, ForeignKey('b.id'), 
primary_key=True)),
                backref="related_a"
            )

class B(Base):
   __tablename__ = 'b'
   id = Column(Integer, primary_key=True)

engine = create_engine("sqlite://", echo=True)

Base.metadata.create_all(engine)
s = Session(engine)

b1, b2, b3 = B(), B(), B()
a1 = A(related=[b1, b2, b3])
s.add(a1)

s.commit()

assert s.query(Base.metadata.tables['secondary']).count() == 3

s.delete(b2)
s.commit()

assert s.query(Base.metadata.tables['secondary']).count() == 2




> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "sqlalchemy" group.
> To post to this group, send email to sqlalchemy@googlegroups.com.
> To unsubscribe from this group, send email to 
> sqlalchemy+unsubscr...@googlegroups.com.
> For more options, visit this group at 
> http://groups.google.com/group/sqlalchemy?hl=en.
> 

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to