Monday, April 25, 2016

Avoid DB Session addition marshmallow object while using marshmallow sql-alchemy object

Leave a Comment

Is there a way to avoid inserting the data into session while using Marshmallow - sqlalchemy

sqlalchemy marshmallow avoid loading into session

Ref: https://marshmallow-sqlalchemy.readthedocs.org/en/latest/

Because we tried to manage the objects by ourself. Will add into the session if required , but for validation I need to use load ()

author = Author(name='Chuck Paluhniuk') book = Book(title='Fight Club', author=author) session.add(author) session.add(book) session.commit()  author_schema.dump(author).data # {'books': [123], 'id': 321, 'name': 'Chuck Paluhniuk'}  author_schema.load(dump_data, session=session).data # <Author(name='Chuck Paluhniuk')> 

The work around to avoid this issue , after I tried with load I can call DB Session.close() to ignore the temporary data. But again I need to get the session to flush the data into DB .

Please advice. Thanks for your help

2 Answers

Answers 1

Adding the object to the session has no bad effect on your code. As you said you're gonna do it yourself later. So there is no differences between adding it manually or by load method.

author = author_schema.load(dump_data, session=session) # now author has been added to session by load method # do whatever you want db.session.commit() # This is enough to write changes you've made # or if you don't want to save anything just db.session.rollback() 

I really didn't get why you want to prevent adding the object to the session by load's method

Answers 2

The call to the schema's load() doesn't automatically add the object to the session:

>>> from models import session >>> from schema import author_schema >>> a = {'id': 1, 'name': 'Chuck Paluhniuk'} >>> obj = author_schema.load(a, session=session) >>> session.new IdentitySet([]) >>> session.add(obj.data) >>> session.new IdentitySet([<Author(name=u'Chuck Paluhniuk')>]) >>> session.commit() >>> session.new IdentitySet([]) >>> session.identity_map.items() [((<class 'models.Author'>, (1,)), <Author(name=u'Chuck Paluhniuk')>)] 

The object must be making it into the session another way. Perhaps you could post some of your code exhibiting the issue?

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment