Michael Bayer wrote:
> chaouche yacine wrote:
>   
>> But how can I be sure that the city of New Jersey will be inserted before
>> the user in the database so that the new user row will get the proper city
>> id ?
>>     
>
> SQLAlchemy takes care of that automatically once you configure the
> relationship between user and city using relation().
>
>
>   
>> So I figured to rewrite the city helper function like this :
>>
>> def city(name):
>>     theCity = City.query.filter_by(name=name).first()
>>     if not theCity :
>>        theCity = City(name=name)
>>        session.commit() # to be sure it will be inserted before the user
>>     return theCity
>>     
>
> if you did go this route (which you don't need to), you probably don't
> want to commit() in the middle of constructing your User object like that
> - the commit() should be held off until the full set of "related things"
> you're constructing have been all put in the database.  that's why its
> called a "transaction".   More appropriate would be flush() which ensures
> everything pending is issued to the current transaction.   Once everything
> is inserted into the database the way you want, "commit" pushes the data
> out to the world, making that data available to other transactions.
>   

Also, there is a recipe that looks for a matching object in the session
before querying the database:
http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject

-Conor

--

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


Reply via email to