python - 是否可以使用 Pydantic BaseModel orm_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'
推荐阅读
- batch-file - 如何批量查找多个特殊字符?
- python - 将 0/1 应用于布尔逻辑
- html - 引导导航 Iphone 12 PRO MAX
- angular - 安装在 Angular 中时 NGRX 11 抛出错误
- javascript - React-Native iOS 为 accesibilityRole VoiceOver 屏幕阅读器提供翻译
- angular - ngx-recaptcha2 一旦添加到 DOM 中就不会刷新验证码
- python - 如何保持 node.js 和 python 之间的连接状态?
- r - R项目WD“自行”改变
- django - 为什么 django-cleanup 会删除使用过的媒体文件?
- ruby-on-rails - 乘客状态导致 SIGSEGV(11),使乘客崩溃,导致 502s