Monday, 15 February 2021

How to use values from list to validate some calculations in pydantic BaseModel?

I'm using Pydantic root_validator to perform some calculations in my model:

class ProductLne(BaseModel):
    qtt_line: float = 0.00
    prix_unite: float = 0.00
    so_total_ht: float = 0.00
    
    class Config:
        validate_assignment = True

    @root_validator()
    def calculat_so_totals(cls, values):
      values["so_total_ht"] = values.get("qtt_line")*values.get("prix_unite")
    
    return values

class Bon(BaseModel):
    articles: List[ProductLne] = []
    total_ht: float = 0.00

    class Config:
        validate_assignment = True

    @root_validator()
    def set_total_ht(cls, values):
        for item in values.get('articles'):
            values['total_ht'] += item.so_total_ht
        return values

some data

 item_line1 = ProductLne(qtt_line=10, prix_unite=10.00)
 item_line2 = ProductLne(qtt_line=10, prix_unite=12.00)
 bon1 = Bon()
 bon1.articles.append(item_line1)
 bon1.articles.append(item_line2)

when run

 print(bon1.total_ht)

i get : 0.0, O.OO Iwant 220

How to make this function return the correct values?



from How to use values from list to validate some calculations in pydantic BaseModel?

No comments:

Post a Comment