Remove an inherited field from a model in pydantic v2 #6699
Replies: 7 comments 11 replies
-
I am struggling with the same question. Currently my approach is to annotate attributes in inherited models as ClassVar as they are then automatically excluded. see https://docs.pydantic.dev/latest/usage/models/#automatically-excluded-attributes But I am not sure what the implications and drawbacks of this approach are. Is it safe? Is it the best way forward? Your example could then look like:
I love some of Pydantic V2's new features (e.g. |
Beta Was this translation helpful? Give feedback.
-
Hi, thanks for your question. See this documentation for how to use the Here's a basic example: from pydantic import BaseModel
from typing import List
class Credentials(BaseModel):
username: str
password: str
class User(BaseModel):
name: str
credentials: Credentials
user = User(name="charles", credentials=Credentials(username="charles123", password="super-secret-pw"))
print(user.model_dump())
# > {'name': 'charles', 'credentials': {'username': 'charles123', 'password': 'super-secret-pw'}}
print(user.model_dump(exclude={"credentials": {"password"}}))
# > {'name': 'charles', 'credentials': {'username': 'charles123'}} Feel free to let me know if you have any follow up questions! |
Beta Was this translation helpful? Give feedback.
-
Can anyone suggest a safe and good way to do this? |
Beta Was this translation helpful? Give feedback.
-
I still don't have a satisfying answer to this problem, but omitting fields as suggested in #8516 could solve this issue too. |
Beta Was this translation helpful? Give feedback.
-
You can redefine the field in the child model, but with Here is the complete code:
Works with pydantic v2.5.0 |
Beta Was this translation helpful? Give feedback.
-
ChatGPT brought me on the idea of using the @model_serialize decorator. Is there anything speaking against using this approach? Is using model_copy not ideal? Example with include (which is nice, because you don't have to remember about excluding potentially sensitive attributes that have been added to the base model later):
|
Beta Was this translation helpful? Give feedback.
-
I'm surprised Pydantic doesn't provide a method to exclude fields in an inherited model out of the box. How can this be raised as a feature request? Relates to: #9573 |
Beta Was this translation helpful? Give feedback.
-
With pydantic v1 it was possible to exclude named fields in the child model if they were inherited from the parent with:
The fields member variable has been removed in pydantic v2, so how can the same functionality be achieved? As a follow up question, what if the field is not inherited but part of a complex type in a model, for example, how to remove the id_ field from the following model in only one use case (CreatTicketOut):
See previous discussion of this topic for pydantic v1: #2686
Beta Was this translation helpful? Give feedback.
All reactions