I'm new to sqlalchemy and only knows basic sqlalachemy knowledge.
Now I'm writing some Python code, what I need to do is like the following:
There is a User table, a Group table and a GroupUser table. To simplify the question, say I have known user id is 100. Now I want to insert a new group into the Group table, and get the group id back, then insert (group_id, user_id) tuple into GroupUser table.
The code I can write is like the following:
# Insert the group first.
session = self.DBSession()
new_group = Group(name = 'gname')
session.add(new_group)
session.commit()
# Then query back the new group id
gid = session.query(Group).filter(Group.name == 'gname').first().id
# At last, insert group-user
gu = GroupUser(gid=gid, uid=100)
session.add(gu)
session.commit()
By the way, id in Group table is autoincrement.
I wonder if this procedure can be simplified? Can I do this in a single transaction.