It is required when you want to enter information on the parent-child relationship of data in the database. For example, a hotel may have multiple rooms tied to it, or a service may have multiple plans tied to it.
The important points are the following two points.
session.add(parent_record) #Transaction registration
session.fluhs() #Registered in DB (not saved)
parent_id = parent_record.id #Get parent ID
At the time of session.add (record), the ID of the parent data has not been assigned, so it cannot be obtained. By doing session.flush (), the parent ID will be assigned and you will be able to get it.
session.add(parent_record)
session.commit() #Registered in DB (saved)
parent_id = parent_record.id #Get parent ID
It can be stored in the database with session.commit () and can be obtained because the parent ID is assigned. However, since the rollback mentioned in important point 2 cannot be performed, if storage fails with child data, a situation will occur in which only the parent data is stored, and it takes time and effort to register the child data. I will end up. (For example, manually assigning a parent ID) If possible, the insert will be more efficient if the parent and child data are committed in the same session.
Recommended Posts