On Dec 2, 2010, at 5:53 PM, Lenza McElrath wrote:
> I ran into an issue where a query was returning a object where the relations
> were stale. It turned out that this is because inserting a row does not
> update relations in identity map. The basic issue looks like this:
>
> my_model = MyModel()
> session.add(my_model)
> session.flush()
> assert len(my_model.related_models) == 0
>
> # Create a RelatedModel that is related to my_model
> related = self.RelatedModel(my_model_id=my_model.id)
> session.add(related)
> session.flush()
>
> # This works
> related_models =
> session.query(RelatedModel).filter_by(my_model_id=my_model.id).all()
> assert len(related_models) == 1
>
> # This will issue a SQL query, but the related model that is returned
> is ignored
> # NOTE: Test will pass if we remove my_model from the session
> #session.expunge(my_model)
> my_model =
> session.query(MyModel).options(sqlalchemy.orm.eagerload('related_models')).one()
> assert len(my_model.related_models) == 1, len(my_model.related_models)
>
> Note that this happens even if you are selected MyModel (instead of creating
> it). A full version of this test can be found here:
> http://pastebin.com/5HFiGrc1
>
> What is the proper way to deal with this issue? It's not as simple as simply
> adding the expunge because the operations are in independent parts of my code
> (that part of the code that creates the related model does not know about
> MyModel). Thanks for any help!
you're making changes via the manipulation of foreign key attributes - SQLA
doesn't link these activities to the state of relationships. You just need to
call Session.expire(MyObject, ['name_of_relationship']) so that the collection
is expired. FAQ on this is at
http://www.sqlalchemy.org/trac/wiki/FAQ#Isetthefoo_idattributeonmyinstanceto7butthefooattributeisstillNone-shouldntithaveloadedFoowithid7
.
>
> -Lenza
>
> --
> You received this message because you are subscribed to the Google Groups
> "sqlalchemy" group.
> To post to this group, send email to sqlalch...@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 sqlalch...@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.