I'm using marshmallow_sqlalchemy library to build object from objects from schemas and then add the database. My Marshmallow and Sqlalchemy classes are defined as follows:
from marshmallow_sqlalchemy import ModelSchema
from marshmallow import fields
class Person(db.Model):
id = db.Column(db.Integer, autoincrement=True, primary_key=True, unique=True)
first_name = db.Column(db.Text)
last_name = db.Column(db.Text)
address = db.Column(db.Text)
class PersonSchema(ModelSchema):
first_name = fields.String(allow_none=False)
last_name = fields.String(allow_none=False)
address = fields.String(allow_none=True)
class Meta:
model = Person
sqla_session = db.session
fields = ('id', 'first_name', 'last_name', 'address')
I have two session; db.session
and session_2
. Objects created through PersonSchema
are attached to db.session
by default. But I need to use session_2
to add those objects to the database:
person_data = {'first_name': 'Bruno', 'last_name': 'Justin', 'Address': 'Street 34, DF'}
person = PersonSchema().load(person_data) # <Person (transient XXXXXXXXXXX)>
If I use db.session
to add this object to db it will work fine:
db.session.add(person)
db.session.commit()
But, when I want to use session_2
like this:
session_2.add(person)
session_2.commit()
I get an this error:
sqlalchemy.exc.InvalidRequestError: Object '<Person at 0x7ff9193e27d0>' is already attached to session '2' (this is '4')
which is expected as objects build with PersonSchema
should be attached to db.session
by default.
My question here is: Is there a way to unbind person
from db.session
to be able to use it with session_2
without changing the definition of PersonSchema
? Or maybe how to override the by default session when calling .load
(I tried .load(person_data, session=session_2)
and it didn't work)? What is the best way to avoid/fix this situation?