Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

python - Can I override fields from a Pydantic parent model to make them optional?

I have two pydantic classes like this.

class Parent(BaseModel):
    id: int
    name: str
    email: str

class ParentUpdate(BaseModel):
    id: Optional[int]
    name: Optional[str]
    email: Optional[str]

Both of these are practically the same but the Parent class makes all fields required. I want to use the Parent class for POST request body in FastAPI, hence all fields should be required. But I want to use the latter for PUT request body since the user can set selective fields and the remaining stays the same. I have taken a look at Required Optional Fields but they do not correspond to what I want to do.

If there was a way I could inherit the Parent class in ParentUpdate and modified all the fields in Parent to make them Optional that would reduce the clutter. Additionally, there are some validators present in the Parent class which I have to rewrite in the ParentUpdate class which I also want to avoid.

Is there any way of doing this? Thanks.

question from:https://stackoverflow.com/questions/65883869/can-i-override-fields-from-a-pydantic-parent-model-to-make-them-optional

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can make optional fields required in subclasses, but you cannot make required fields optional in subclasses. In fastapi author tiangolo's boilerplate projects, he utilizes a pattern like this for your example:

class ParentBase(BaseModel):
    """Shared properties."""
    name: str
    email: str

class ParentCreate(ParentBase):
    """Properties to receive on item creation."""
    # dont need id here if your db autocreates it
    pass

class ParentUpdate(ParentBase):
    """Properties to receive on item update."""
    # dont need id as you are likely PUTing to /parents/{id}
    # other fields should not be optional in a PUT
    # maybe what you are wanting is a PATCH schema?
    pass

class ParentInDBBase(ParentBase):
    """Properties shared by models stored in DB - !exposed in create/update."""
    # primary key exists in db, but not in base/create/update
    id: int                             

class Parent(ParentInDBBase):
    """Properties to return to client."""
    # optionally include things like relationships returned to consumer
    # related_things: List[Thing]
    pass

class ParentInDB(ParentInDBBase):
    """Additional properties stored in DB."""
    # could be secure things like passwords?
    pass

Yes, I agree this is incredibly verbose and I wish it wasn't. You still likely end up with other schemas more specific to particular forms in your UI. Obviously, you can remove some of these as they aren't necessary in this example, but depending on other fields in your DB, they may be needed, or you may need to set defaults, validation, etc.

In my experience for validators, you have to re-declare them but you can use a shared function, ie:

def clean_article_url(cls, v):
    return clean_context_url(v.strip())

class MyModel(BaseModel):
    article_url: str

    _clean_url = pydantic.validator("article_url", allow_reuse=True)(clean_article_url)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...