python - Can SQLAlchemy's session.merge() update its result with newer data from the database? -


The SQLEEE documentation says, "The present state of an example and its related children were made in collaboration with existing data in the database is."

Does the existing object update with the new data from the database? how? when?

SQLLM has created a single object with each identity in the session. But sometimes you have to recreate something with a known identity, eg. When you get it from the network or when you apply offline lock to avoid long transactions. And when you make an object with known identities that may exist in the database, then there is a chance that the session already tracks an object with this identity. This is what is meant for the merge () method: it engages an object with the session, thus avoiding duplicate objects with the same identification in the session. Below is an example of what is going on: sqlalchemy.orm import * metadata = metadata () T = table ('t', metadata, column ('id', integer, primary_key = true), column ('state ', String (10)), square model: pass mapper (model, t) engine = create_engine (' sqlite: // ') metadata.create_all (engine)) session = sessionmaker (bind = engine) () obj1 = Model () obj1.state = 'value1' session.add (obj1) session.commit () obj_id = obj1.id obj2 = model obj2.id = obj_id obj2 .state = 'value2' obj3 = session.merge ( Obj2) session.commit () print is obj3 obj1, obj3 obj2 print obj3.state

output is:

True False value2

Thus session.merge (obj2) shows that an object with the same identity (Made up of obj1 ), so it merged into the existing code in the obj2 and gives it back.

Below is another example, ate from database:

  # ... left ... t = table ('t', metadata, column (' Column ('state2', string (10)), column ('state2', string (10)) ... left ... left ... obj1 = 'id', integer, primary_key = true) Model () obj1.state1 = 'value1-1' obj1.state2 = 'value2-1' Session.add (obj1) session.commit () obj_id = obj1.id session.expunge_all () obj2 = model obj2.id = Obj_id obj2.state1 = 'value1-2' obj3 = session.merge (obj2) session .comit () print obj3 obj1, obj3 obj2 print obj3.state1, obj3.state2  

Output is:

  false false value of 1-2 value2-1  

Now the object with the same identity was not found in the session, because we dismissed it. Also I partially created a new object with fixed state, but the rest is loaded from the database.


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

php - jQuery AJAX Post not working -