Reputation: 53
I have 2 Pydantic classes
class AuthenticatedCreateBasketV2ApiModel(PublicCreateBasketV2ApiModel):
agency: str = Field()
owner: Optional[UserUuid] = Field()
effective_date: Date
class PublicCreateBasketV2ApiModel(BaseModel):
agency: str
changes: conlist(ChangeApiModel, min_items=1)
effective_date: Date
email: Optional[EmailStr] = None
class Config:
extra = "forbid"
and I am trying to validate like so AuthenticatedCreateBasketV2ApiModel(effective_date=effective_date, changes=[change])
with my validator
@validator("changes")
def validate_changes_for_lapse_or_renewal_or_cancellation(
cls, changes: List
) -> List[Change]:
lapse_changes, renewal_changes, cancellation_changes = [], [], []
for change in changes:
if change.type == ChangeType.LAPSE:
lapse_changes.append(change)
elif change.type == ChangeType.RENEW:
renewal_changes.append(change)
elif change.type == ChangeType.CANCEL:
cancellation_changes.append(change)
validate_lapses(lapse_changes)
validate_renewals(renewal_changes)
validate_cancellations(cancellation_changes)
return changes
The problem is that I can't seem to access effective_date
in my validator. I have tried using the code examples here to no avail. Any advice would be appreciated
Upvotes: 0
Views: 2904
Reputation: 4099
The problem is that I can't seem to access effective_date in my validator
Add the values
argument and make sure that effective_date
is before changes
. From the documentation:
you can also add any subset of the following arguments to the signature (the names must match):
values
: a dict containing the name-to-value mapping of any previously-validated fields[...]
where validators rely on other values, you should be aware that:
- Validation is done in the order fields are defined.
Example:
class PublicCreateBasketV2ApiModel(BaseModel):
effective_date: Date # This field should be before the changes field if you want to access it in a @validator("changes")
changes: conlist(ChangeApiModel, min_items=1)
@validator("changes")
def validate_changes_for_lapse_or_renewal_or_cancellation(cls, changes: List[ChangeApiModel], values: Dict[str, Any]) -> List[ChangeApiModel]:
effective_date = values.get("effective_date") # effective_date = values["effective_date"] might raise a KeyError if effective date was not valid
if effective_date is None:
# effective_date is not available because it was not valid. Handle this case.
# Continue validation
return changes
Upvotes: 1