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.
Joril
问问题
3549 次
3 回答
23
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
于 2014-07-29T09:05:24.683 回答
5
I think you could look at the child's __dict__
attribute dictionary to check if the data is already there or not.
于 2008-11-04T07:48:26.470 回答
3
Slightly neater than Haes answer (though it effectively does the same thing) is to use hasattr(), as in:
>>> hasattr(X, 'children')
False
于 2013-01-15T10:34:28.860 回答