Pydantic继承的班级验证

发布于 2025-01-22 08:24:44 字数 1499 浏览 1 评论 0原文

我有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"

,我正在尝试像so authenticatiCateCteCreateBaskEtv2apimodel(有效_DATE =效率=有效_DATE,更改= [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

,我似乎无法访问有效>在我的验证器中。我尝试使用代码示例在这里无济于事。任何建议将不胜感激

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千纸鹤 2025-01-29 08:24:44

问题是我似乎无法在验证器中访问有效_date

添加value参数,并确保有效_date更改之前。来自文档

  • 您还可以将以下参数的任何子集添加到签名中(名称必须匹配):

    • values:一个包含任何先前验证字段的名称对值映射
    • 的dict

[...]

  • 如果验证者依赖其他值,则应知道:

    • 在订单字段中定义验证。

例子:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文