Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

fastapi - Declare fast api, python's object

Can we declare a model that inherits basemodel and put a value in it, not a normal Python model?

I can forcefully create a PyTimeZoneSetting model, but can I use the existing TimeZoneSetting?

    from pydantic import BaseModel
    from typing import List, Optional

    class TimeZoneSetting(BaseModel):
        time_zone: str
        type: int
        sync_time: Optional[str] = None
        time_server: Optional[str] = None
        time_set_type: Optional[int] = None

    class PyTimeZoneSetting():
        time_zone: str
        type: int
        sync_time: str
        time_server: str
        time_set_type: str

    def update_system_timezone():
        !Here, I want to create a TimeZoneSetting model and put in a value.!

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

1 Answer

0 votes
by (71.8m points)

I am not quite sure of your intentions bu I will try to provide an example which could fulfill your needs.

Here are some ways you could initialize your Pydantic Model:

# initialize every field one by one
model_instance = TimeZoneSetting(time_zone="foo", type=1, sync_time="bar")

# provide your dict object
kwargs = {"time_zone": "foo", "type": 1}
model_instance = TimeZoneSetting(**kwargs)

Here is the way to update your model, where every field is reached as an attribute to your class:

model_instance.time_zone = "bar"

Here is the way to get you model as a dict:

model_instance.dict()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...