I want to filter relationships in a query, but I can't because the ModelConverterBase._prepare_select_options function generates the query in a hardcode.
class CustomModelConverter(ModelConverter):
select_option_stmts = {
'field': select(Model).where(Model.level > 1)
}
class ModelBaseConverter:
select_option_stmts: Dict[str, Select]
async def _prepare_select_options(
self,
prop: RelationshipProperty,
session_maker: sessionmaker,
) -> list[tuple[str, Any]]:
target_model = prop.mapper.class_
if prop.key in self.select_option_stmts:
stmt = self.select_option_stmts[prop.key]
else:
stmt = select(target_model)
if is_async_session_maker(session_maker):
async with session_maker() as session:
objects = await session.execute(stmt)
return [
(str(self._get_identifier_value(obj)), str(obj))
for obj in objects.scalars().unique().all()
]
else:
with session_maker() as session:
objects = await anyio.to_thread.run_sync(session.execute, stmt)
return [
(str(self._get_identifier_value(obj)), str(obj))
for obj in objects.scalars().unique().all()
]
class View(ModelView, model=Model):
form_converter = CustomModelConverter
There is an option to inherit from ModelConverter and override the _prepare_select_options method in CustomModelConverter. But it looks like a huge crutch.
class CustomModelConverter(ModelConverter):
async def _prepare_select_options(
self,
prop: RelationshipProperty,
session_maker: sessionmaker,
) -> list[tuple[str, Any]]:
target_model = prop.mapper.class_
stmt = <custom query>
if is_async_session_maker(session_maker):
async with session_maker() as session:
objects = await session.execute(stmt)
return [
(str(self._get_identifier_value(obj)), str(obj))
for obj in objects.scalars().unique().all()
]
else:
with session_maker() as session:
objects = await anyio.to_thread.run_sync(session.execute, stmt)
return [
(str(self._get_identifier_value(obj)), str(obj))
for obj in objects.scalars().unique().all()
]
class View(ModelView, model=Model):
form_converter = CustomModelConverter
No response
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too