I am writing a simple serializer for SQLAlchemy instances into Python dictionaries and am trying to serialize only objects that were eagerly loaded, but excluding objects that were not. More specifically, I am trying to check the load options of a relationship of a SQLAlchemy object retrieved from a query with custom load options. For e.g.
class Item(db.Model):
...
field = db.relationship('Field', lazy='raise')
item = session.query(Item).options([joinedload(Item.field)]).first()
Now I expect the Item.field relationship to have a lazy='joined' because I overrode the load options at query time, but when I check in item._sa_instance_state.mapper.relationships.get('field').lazy
, it is still a 'raise'
.
In other words, it seems like SQLAlchemy's query load options is converted into SQL but does not affect the instance's state's load options at all.
- I have considered the use of
item._sa_instance_state.unloaded
as an indicator of whether or not something has been joinloaded. If it was joinloaded, then the field will not be initem._sa_instance_state.unloaded
. Is this correct? - If something has been
noload
,raiseload
orselect
, would they ever not be initem._sa_instance_state.unloaded
before being accessed?
Could someone please enlighten me if there is a better way of detecting the load options of an instance after querying please?