I've been surprised by some SA behavior that doesn't seem quite right
to me so I thought I'd post about it.  I have submitted a trac ticket
(#1201) which has example source code against sqllite, and its been
closed as not a problem (if I understand).  I'm fine with that, I just
still don't completely understand or agree that this is desirable
behavior. I'm new to SA so this may just be a problem with my
viewpoint.  Ticket is at http://www.sqlalchemy.org/trac/ticket/1201.

The situation is that there is one child table with two parent tables,
and we want to add the child to both parents.

One way to do this (which works, so this is one workaround) is to set
both parents at once on the child and then save it:
   child = Child(parent = p, parent2 = p2, ...)
   DBSession.save(child)

OK.

What surprised me was that I couldn't do this another way - by setting
one parent on the child directly and then adding the child to the
other parent's collection:

    p = DBSession.query(Parent).filter(...).one()

    p2 = DBSession.query(Parent2).filter(...).one()

    # uncommenting this prevents the error
    # print p.children

    c = Child(name=u'the child', parent2=p2)

    p.children.append(c)

As is, this code causes an exception at the final
"p.children.append(c)" line, the error being that the foreign key to
Parent has not been set (it's the database complaining since the fk is
not nullable).

If however the p.children attribute is forced to load before the final
line, by either eagerloading "children" attribute in the query for p,
or by just printing p.children, then there is no error.  Also no error
of course if the classes/tables are modified so that there is no
second parent at all.  I don't see how the presence of the second
parent in the design seems to cause the main parent not to adopt the
child.  I don't really understand the connection to autoflushing that
the trac item mentioned, either (and I don't have an autoflush
attribute on my scoped session, it appears).

I do want to thank zzzeek who very quickly provided workarounds in the
trac entry.

Thoughts?  Is this the way it should be?

-Steve


--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to