Feature Request: built-in validator that object already exists in the db (useful for foreign keys)
See original GitHub issueSome of my API’s let people create new objects, and some of the fields are optional foreign keys. Currently when a foreign key gets passed in, I have some custom validators that check the database to verify that the FK object actually exists. I could catch the exception, but rather check it on initial POST/PATCH.
This strikes me as something that would be useful as a built-in validator for marshmallow-sqlalchemy
I think the implementation would be fairly straightforward, although it’s an open question in my mind whether to use session.query(foreign object).options(load_only(pk_field)).get(pk id)
or something a little more fancy like:
if not db.session.query(db.exists([GearCategory.id]).where(GearCategory.id == category_id)).scalar():
raise Exception("Gear Category ID [%s] does not exist" % category_id)
The get()
will be far faster when the object is already in the session, but slower than the EXISTS
if the query has to actually hit the DB.
Issue Analytics
- State:
- Created 8 years ago
- Reactions:3
- Comments:6 (1 by maintainers)
Top GitHub Comments
The code below is my solution for all foreign fields. It’s strange that this is not in the library. I will be glad to see suggestions for improving this code.
No problem, see the
category_id
line for how I used it: