Replies: 4 comments
-
@ankithherle you have closed this issue but what is the solution you came up with? I'm faced with the same question currently. |
Beta Was this translation helpful? Give feedback.
-
@madisvain You generally shouldn't be performing any IO inside pydantic validators. In particular, I would advise against doing anything that involves a database query inside model validation logic. This is because validators are executed eagerly, and may be executed in an async context where the IO would end up blocking your server's event loop, with huge negative performance impacts. Instead, you should perform any IO-related checks prior to model validation, and do any related error handling manually. If you need to reuse the functionality, I'd recommend creating a function that accepts a sqlalchemy Session, and returns the model you want. I believe this has been discussed in several other issues in the fastapi and pydantic repos; if you search for related issues you might find more detail/justification for this. |
Beta Was this translation helpful? Give feedback.
-
@dmontagu thank you very much for your response. Coming from a Django and DRF background this is what you do (not to say that it's ok). Currently what the example library had as an example was raising a HttpError. I wanted to keep the error output same to what Pydantic was outputting as validation errors so I figured out how to raise validation errors and do this outside of the validators.
This way I can use the same error checking logic in the frontend throughout the whole request. |
Beta Was this translation helpful? Give feedback.
-
Yeah, that makes sense. I also came from Django+DRF originally, and I've really come to appreciate how easy it is to reason about performance implications using pydantic since everything tends to be explicit and eager. I think your solution makes sense, and it would be nice if it were a little easier to manually instantiate errors like this for precisely the reason you've identified. I think there has been some discussion of this over in pydantic, I'm not sure what the state of affairs is though. |
Beta Was this translation helpful? Give feedback.
-
I want to validate a field against the database., i.e. Check Whether a field exists in the database's table (similar to Marshmallow)?
I am using
SQLalchemy
as the ORM, Is it possible to write such validators withPydantic
My code sample looks like
Currently, it is not working, Is this type of validator allowed in pydantic ? How to use it ?
Beta Was this translation helpful? Give feedback.
All reactions