Field customisation for nested and inherited models in Pydantic

Viewed 828

I've thoroughly searched for an answer for this query, with little avail.

Using pydantic, the ge=0 validation of item_main in the following example proceeds without a hitch, would be expected (as per instructions: https://pydantic-docs.helpmanual.io/usage/schema/#field-customisation):

class SubCls(BaseModel):
    item_sub: float = Field(...)

class MainCls(BaseModel):
    item_main1: float = Field(...)
    item_main2: SubCls

    class Config:
        fields = {'item_main1': {'ge': 0}}

However, the ge=0 validation of nested item_sub in the following example does not work:

class SubCls(BaseModel):
    item_sub: float = Field(...)

class MainCls(BaseModel):
    item_main1: float = Field(...)
    item_main2: SubCls

    class Config:
        fields = {'item_main2': {"item_sub":{'ge': 0}}}

Neither does it when SubCl is inherited by MainCls:

class SubCls(BaseModel):
    item_sub: float = Field(...)

class MainCls(SubCls):
    item_main1: float = Field(...)

    class Config:
        fields = {"item_sub":{'ge': 0}}

I am wondering how I can best apply field customisation to nested models. Of course, the most elegant way to do it is to create a new SubCls models, with the validation information added, but in my use case this would lead to a rather excessive number of models. I'd be grateful for any help.

This query has been cross-posted on pydantic's github forum: https://github.com/samuelcolvin/pydantic/discussions/3400.

0 Answers
Related