Prevent garbage collection of the joined record #1217
-
First Check
Commit to Help
Example Codeclass PatientsRepository:
async def fetch_one(self, pk: UUID | None = None, **kwargs: Any) -> tuple[Patient, User]:
stmt = select(Patient, User).join(User).where(Patient.id == pk)
result = await self.db.exec(stmt)
obj = result.first()
return obj
async def create(self, obj: Patient) -> tuple[Patient, None]:
self.db.add(obj)
await self.db.flush()
patient, user = await self.fetch_one(pk=obj.id)
self._loaded_related.append(user)
return patient, None DescriptionI'm using a select with join to retrieve related model. After I return parent model from the repository method, the child model garbage collected (and it sound reasonable). So To solve this, I store related model to the class property Are there any other clear way to do so? Don't want to return both records from the repository method cause I want a clear interface (and will still have to deal with gc above on the stack anyway). Operating SystemmacOS Operating System DetailsNo response SQLModel Version0.0.22 Python VersionPython 3.12.7 Additional ContextI believe there is no issue with SQLModel of SQLAlchemy, just trying to find a better approach. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Use async def fetch_one(self, pk: UUID | None = None, **kwargs: Any) -> Patient:
return await session.get(Patient, pk, options=[selectinload(Patient.user)]) |
Beta Was this translation helpful? Give feedback.
Use
selectinload
to properly pre-load relationships: