Pydantic Inherited Class 验证

Pydantic Inherited Class validation

我有 2 个 Pydantic 类

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"

我正在尝试这样验证 AuthenticatedCreateBasketV2ApiModel(effective_date=effective_date, changes=[change])

与我的验证器

    @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

问题是我似乎无法在我的验证程序中访问 effective_date。我尝试使用代码示例 here 无济于事。任何建议将不胜感激

The problem is that I can't seem to access effective_date in my validator

添加 values 参数并确保 effective_datechanges 之前。来自 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.

示例:

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