是否可以使用Pydantic BaseModel或m_mode从gui类获取数据?



是否可以使用继承自Pydantic的模型类?BaseModel通过设置orm_mode= true从GUI类获取数据,就像使用数据库一样

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

"如果可能的话,我该怎么做呢?

假定ORM mode支持任意类,而不仅仅是数据库ORM(这样命名是因为它通常与它结合使用)。

正则类的例子:

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'