[ACCEPTED]-How to find out if a lazy relation isn't loaded yet, with SQLAlchemy?-sqlalchemy

Accepted answer
Score: 22

You can get a list of all unloaded properties 3 (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 2 easier way is to use inspect(), which gives the same 1 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
Score: 5

I think you could look at the child's __dict__ attribute 2 dictionary to check if the data is already 1 there or not.

Score: 3

Slightly neater than Haes answer (though 2 it effectively does the same thing) is to 1 use hasattr(), as in:

>>> hasattr(X, 'children')

More Related questions