How to find out if a lazy relation isn't loaded yet, with SQLAlchemy?
-
06-07-2019 - |
Question
With SQLAlchemy, is there a way to know beforehand whether a relation would be lazy-loaded?
For example, given a lazy parent->children relation and an instance X of "parent", I'd like to know if "X.children" is already loaded, without triggering the query.
Solution
I think you could look at the child's __dict__
attribute dictionary to check if the data is already there or not.
OTHER TIPS
You can get a list of all unloaded properties (both relations and columns) from sqlalchemy.orm.attributes.instance_state(obj).unloaded
.
See: Completing object with its relations and avoiding unnecessary queries in sqlalchemy
An easier way is to use inspect()
, which gives the same results:
from sqlalchemy import inspect
from sqlalchemy.orm import lazyload
user = session.query(User).options(lazyload(User.articles)).first()
ins = inspect(user)
ins.unloaded # <- set or properties that are not yet loaded
Slightly neater than Haes answer (though it effectively does the same thing) is to use hasattr(), as in:
>>> hasattr(X, 'children')
False