-
Notifications
You must be signed in to change notification settings - Fork 94
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature Request: built-in validator that object already exists in the db (useful for foreign keys) #50
Comments
Edit #2 After spending a few more days on this, I now understand the original request and would also benefit from such functionality. @jeffwidman - if you wouldn't mind, I would greatly benefit from seeing an example foreign key validator as I'm just not smart enough to figure this out on my own. |
No problem, see the
|
@jeffwidman - Thanks! I actually figured out validators late last week (through brute force and sheer luck) and here was my take on this (feedback welcome).
I'm using this for a RESTful API, and one of the shortcomings I've come across is that I need separate schemas defined for read (GET) vs write (POST/PUT) operations, as I don't want to allow nested schemas to have attributes updated. It works but it's clunky. This validator has been a huge help. I appreciate you posting your code - I may steal some/all of your concepts once I can fully digest/understand them. Thanks again! Wes |
That works, although I wouldn't use the private api |
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.
|
Inspired by @whoiswes but doesn't have any references to private members and shouldn't make additional DB calls. Currently limited to single primary keys. `def validate_fk(rel):
|
Some 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:The
get()
will be far faster when the object is already in the session, but slower than theEXISTS
if the query has to actually hit the DB.The text was updated successfully, but these errors were encountered: