BDMS 22: Implement the sample model in SQLAlchemy POC so that a set of staging data can be displayed in data manager#62
Conversation
This enables the same validations to be used for both adding and updating samples, ensuring consistency and reducing code duplication.
POST and PATCH requests require the same field validators, so we inherit the validators from a base model class for both request types.
| # are sample top/bottom really working as expected? | ||
|
|
||
| @field_validator("sample_top", check_fields=False) | ||
| def validate_sample_top(cls, sample_top: float | None, values) -> float | None: |
There was a problem hiding this comment.
Instead of using field validators for sample top / sample bottom, could you use a @model_validator that runs once on multiple fields after pydantic does its other validations, like:
class CreateSample():
...
@model_validator(mode='after')
def validate_sample_topbottom(self) -> 'CreateSample':
"""
validate sample_top and sample_bottom are provided together
"""
if (self.sample_top is not None and self.sample_bottom is None) or \
(self.sample_bottom is not None and self.sample_top is None):
raise ValueError("Both sample_top and sample_bottom must be defined together")
return self
Would this help with logic duplication between top and bottom field validators?
There was a problem hiding this comment.
@model_validator is probably the way to go. One of the things that I like about @field_validator is that it indicates in the response which fields were invalid and why, so if you want to display the error message beneath (or near) the invalid field it's easy for you.
In the response from @field_validator, for example, the invalid field is pointed to by "loc": ["body", "sample_bottom"]
Nevertheless, from reading forums and chatting with CoPilot @model_validator seems to be the best way to perform cross-field validations. And, if you want to proceed with error messages next to/near invalid fields, we can figure out how to do that efficiently/correctly with @model_validator
- test custom pydantic validations on their own - handle db errors, like foreign key violations, at the API level and test those cases - use model_validator for cross-field validations for sample top and sample bottom - test response against the payload, not response against response
jirhiker
left a comment
There was a problem hiding this comment.
looking good. a few minor change requests
Why
This PR addresses the following problem / context:
How
Implementation summary - the following was changed / added / removed:
Notes
Any special considerations, workarounds, or follow-up work to note?