Search code examples
pydantic

how to hide field from pydantic field but still can access


User object has p and h field, I need to initial this two field.

class User(BaseModel):
    p: str
    h: str = Field(hidden=True)
    #_g: str = PrivateAttr()
    @staticmethod
    def schema_extra(schema: Any, _):
        print('HERE NOT WORK!')
        props = {}
        for k, v in schema.get('properties', {}).items():
            if not v.get("hidden", False):
                props[k] = v
        schema["properties"] = props
    model_config = ConfigDict(json_schema_extra=schema_extra)

s = User(p='1',h='2')

I don't want to return h when using s.model_dump()

and still need to acces h in my code s.h

I hope return json is {'p':'1'}

print('HERE NOT WORK!') not work , that is strange.

pydantic==2.5.2

pydantic_core==2.14.5


Solution

  • I seems you want to just use the Field(exclude=...) option:

    from pydantic import BaseModel, Field
    
    class User(BaseModel):
        p: str
        h: str = Field(exclude=True)
    
    
    s = User(p="1", h="2")
    print(s.model_dump())
    print(s.h)
    

    Which prints:

    {'p': '1'}
    2
    

    I hope this helps!