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
467 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 Reply

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()

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

1.4m articles

1.4m replys

5 comments

56.9k users

...