Filtering relationships in the edit form #712
Replies: 2 comments
-
I would also like the same capability, it would be very useful. |
Beta Was this translation helpful? Give feedback.
-
Hey there, we've successfully filtered relationships in the edit form by passing in a custom class to the from sqladmin.forms import ModelConverter, converts
from path.to.utils import selected_parent_id_var # This is a context var we use for state, set elsewhere
class ChildrenConvert(ModelConverter):
@converts("MANYTOMANY", "ONETOMANY")
def convert_many_to_many(self, model, prop, kwargs):
try:
selected_parent_id = int(selected_parent_id_var.get())
target_model = prop.mapper.class_
with db_session() as db:
if prop.key == "siblings":
query = (
select(target_model)
.join(Parent, target_model.parent_id == Parent.id)
.filter(Parent.id == selected_parent_id)
)
data = [
(str(obj.id), str(obj))
for obj in db.execute(query).scalars().all()
]
kwargs["data"] = data
except LookupError as exc:
logging.exception(exc)
finally:
return QuerySelectMultipleField(**kwargs) Note that this is adapted to the example that you've given, and I haven't tested it. The main concept here is that in the converter function, you have access to the relationships as they're being loaded, and you can filter them at that point. |
Beta Was this translation helpful? Give feedback.
-
I would like to filter/limit the number of choices that are shown for a relation ship in an edit form based on another field on the model.
For example one might be able to select a favorite sibling. The edit form should then just show siblings from the same parent. Currently it would show children of other parents as well.
Is there an obvious way to do this?
Beta Was this translation helpful? Give feedback.
All reactions