Sqlalchemy reload entity with joins

Viewed 35

I'm using sqlalchemy 1.4 orm with Postgres SQL behind. my API endpoints have quite a few domain-specific validation steps where numerous entities are being queried. These validation services are represented by implementations of an abstract class, thus do not really know what the others are doing, yet still relying on the same session (session is part of the "interface").

I am now facing the following issue, assuming the following DB model:

class A:
  id: int
  foo: str
  childs: List[B] = relationship(... 'noload')
  ...

class B:
  id: int
  ...  

in the series of validator steps, the first validator queries an entity from A (e.g. with session.get(1)) just validating the property 'foo'. Subsequently the next validator again queries A with id==1 but with .options(joinedload(dbm.A.childs)) - to ensure that no child exists or whatever.

I now face the issue, that since A(id.1) has already been loaded in the first step, the joinedload in the second step is simply ignored and always returns an empty list. In case I expunge the object before, obviously, everything works fine.

Of course, I know what I'd like to do may lead to several, possibly redundant queries to the database, but in my scenario (since the validation steps are rather complex), the code structure is more important to me than overall response time, especially since it only occurs in some mutation endpoints and the queries are usually quite trivial anyway (key lookups, maybe load some childs or so).

Is there any way, besides always expunging the object to ensure that the childs are loaded in the second step (maybe some configuration or so)?

0 Answers
Related