I'm trying to load and serialize a deeply nested model using SQLAlchemy into a json response (using pydantic ParentType), which seems difficult using an async engine.
I have a Parent db model, which is related to a Child, which in turn is related to GrandChild and so on...
Now, I can eagerly load the 1st level of relationships using:
stmt = select(Parent).filter(Parent.id == id)
stmt = stmt.options(joinedload(getattr(Parent, "children")))
But this will fail because Child's children will need to be lazy-loaded.
I can eager load every relation of my Parent model recursively and so on... but this method will go past my required depth of ParentType and will result in extra queries that I do not need.
How can I lazy-load in async according to my serialization model?
Options:
- To pair the serialization model and eager load the required relations?
- Somehow create a new greenlet to fetch the relation?