[Python] Excluding fields on a pydantic model when it is the nested child of another model

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    I have a pydantic model that I want to dynamically exclude fields on.

    I can do this by overriding the dict function on the model so it can take my custom flag, e.g.:

    class MyModel(BaseModel):
    field: str

    def dict(self, **kwargs):
    if ('exclude_special_fields' in kwargs):
    super().dict(exclude={"field": True}, **kwargs)

    super().dict(**kwargs)


    However, this does not work if my model is a child of another model that has .dict called on it:

    class AnotherModel(BaseModel):
    models: List[MyModel]

    AnotherModel(models=[...]).dict(exclude_special_fields=True) # does not work


    This is because when MyModel.dict() is called, it isn't called with the same arguments as the parent.

    I could write a dict override on the parent model too to specify an exclude for any child components (e.g. exclude={"models": {"__all__": {"field": True}}}), but in my real world example, I have many parent models that use this one sub-model, and I don't want to have to write an override for each one.

    Is there anyway I can ensure the child model knows when to exclude fields?

    Extra context

    Extra context not completely important to the question, but the reason I want to do this is to exclude certain fields on a model if it's ever returned from an API call.

    Continue reading...

Compartilhe esta Página