最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

automatically convert a field in pydantic class - Stack Overflow

programmeradmin3浏览0评论

I want to use pedantic (2.14.6) to create a BaseModel class called "Bar." I want to be able to initialize it with 2 ints and convert the latter to a "Price". On the following code I get the error on the last line: Expected type 'Price', got 'int' instead

from pydantic import BaseModel, field_validator

class Price:
    def __init__(self, value: int):
        self.value = value * 10

    def __str__(self):
        return f"{self.value}"

class Bar(BaseModel):
    price1: int
    price2: Price

    @field_validator("price2")
    def convert_to_price(cls, value):
        if isinstance(value, int):
            return Price(value)
        elif isinstance(value, Price):
            return value
        raise ValueError("err")

bar = Bar(price1=100, price2=100)    # I get: Expected type 'Price', got 'int' instead 
print(bar)
发布评论

评论列表(0)

  1. 暂无评论