How to validate data depending on another property #2498
-
I have a list of platforms and with a list of valid platforms for platform, as seen at https://github.com/ansible-community/schemas/blob/main/src/ansibleschemas/_galaxy.py I do want to enable validation of these values, so users will be notified if they put an invalid version for a specific platform. Current model looks like: class PlatformModel(BaseModel):
name: str
versions: List[str] # user can specify a list of versions I do know how to make platform be an enum, but this would not allow me to limit the versions to allow only those versions permitted by that specific platform. |
Beta Was this translation helpful? Give feedback.
Answered by
PrettyWood
Mar 9, 2021
Replies: 1 comment 3 replies
-
Hi @ssbarnea from pydantic import BaseModel, validator
VALID_VERSIONS = {'q', 'w'}
class PlatformModel(BaseModel):
name: str
versions: list[str]
@validator('versions', each_item=True)
def valid_version(cls, v: str) -> str:
if v not in VALID_VERSIONS:
raise ValueError(f'{v!r} is not a valid version')
return v
PlatformModel(name='qwe', versions=['a', 'w', 'b', 'q'])
# pydantic.error_wrappers.ValidationError: 2 validation errors for PlatformModel
# versions -> 0
# 'a' is not a valid version (type=value_error)
# versions -> 2
# 'b' is not a valid version (type=value_error) Hope it helps! |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
ssbarnea
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @ssbarnea
You could just use
validator
Hope it helps!