On 7/24/2010 8:21 AM, manman wrote:
table A,B
B.a_id=A.id
my code like this:
new_a=A()
session.begin()
session.add(new_a)
new_b=B()
new_b.a_id=new_a.id
session.add(new_b)
try:
session.commit()
except:
session.rollback()
raise
why new_b.a_id is None? how to do?
I presume a.id is an autoincrement field, in which case it isn't given a
value until a session.flush() occurs. So this should work:
new_a = A()
session.begin()
session.add(new_a)
session.flush()
new_b = B()
new_b.a_id = new_a.id
session.add(new_b)
session.commit()
session.flush() happens automatically as part of session.commit(), but
an explicit one is needed for the autoincrement ID to be generated ahead
of time in this case.
Also if you set up a relationship between the classes you could avoid
the problem as well:
mapper(A, a_table)
mapper(B, b_table, properties=dict(a=relation(A)))
new_a = A()
session.begin()
session.add(new_a)
new_b = B()
new_b.a = new_a
session.add(new_b)
session.commit()
Note the object assignment instead of assigning an ID this time.
Lance
--
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=en.