Pydantic 验证器中迭代上下文中使用的不可迭代值

问题描述 投票:0回答:1

我有一个 Pydantic DTO,看起来像这样:

from pydantic import AfterValidator, model_validator, BaseModel

class Bid(BaseModel):

    start_block: Annotated[DateTime, AfterValidator(block_validator)]

    end_block: Annotated[DateTime, AfterValidator(block_validator)]

    threshold: int

    pq_pairs: Annotated[List[PriceQuantityPair], AfterValidator(pq_pair_validator)] = Field(min_length=1)

    @model_validator(mode="after")
    def validate_bid(self) -> Self:
        """Validate an offer."""
        # Check that the start block is before the end block
        if self.start_block >= self.end_block:
            raise ValueError("The start block must be before the end block.")

        for pq_pair in self.pq_pairs:
            if self.threshold > pq_pair.quantity:
                raise ValueError("The threshold must be less than or equal to the quantity.")

        # Return the object now that we've validated it
        return self

这工作正常,但 Pylint 引发了一个 linting 错误:

E1133:不可迭代值 self.pq_pairs 在迭代上下文中使用(不可迭代)

我认为这与

Annotated
的使用有关,但我不知道该怎么办。任何帮助将不胜感激。

python pydantic pylint
1个回答
0
投票

花了一段时间,但经过一些实验我发现了!通过以下方式定义

pq_pairs
可以解决问题:

class Bid(BaseModel):
    pq_pairs: Annotated[List[PriceQuantityPair], AfterValidator(pq_pair_validator), Field(min_length=1)]

假设将

Field
分配给混淆 pylint 的属性。

© www.soinside.com 2019 - 2024. All rights reserved.