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
253 views
in Technique[技术] by (71.8m points)

python - Is it possible to use Pydantic BaseModel orm_mode to get data from gui class

Is it possible to use model class which inherit from Pydantic.BaseModel to get data from a GUI class by setting orm_mode= true, like it used with databases

from typing import List
from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.declarative import declarative_base
from pydantic import BaseModel, constr

Base = declarative_base()


class CompanyOrm(Base):
    __tablename__ = 'companies'
    id = Column(Integer, primary_key=True, nullable=False)
    public_key = Column(String(20), index=True, nullable=False, unique=True)
    name = Column(String(63), unique=True)
    domains = Column(ARRAY(String(255)))


class CompanyModel(BaseModel):
    id: int
    public_key: constr(max_length=20)
    name: constr(max_length=63)
    domains: List[constr(max_length=255)]

    class Config:
        orm_mode = True

'''' If it is possible how may i do it ?

question from:https://stackoverflow.com/questions/65933912/is-it-possible-to-use-pydantic-basemodel-orm-mode-to-get-data-from-gui-class

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

1 Reply

0 votes
by (71.8m points)

It is assumed that ORM mode supports arbitrary classes, not just databases ORM (it is named so because it is usually used in conjunction with it). More detailed here.

Example with regular class:

from pydantic import BaseModel


class SomeClass:
    def __init__(self):
        self.id = 100
        self.name = "some_name"


class SomeModel(BaseModel):
    id: int
    name: str

    class Config:
        orm_mode = True


print(SomeModel.from_orm(SomeClass()))  # id=100 name='some_name'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...