如何使我的其他类在PYDANC2.0中成为可选的?当我有数据时,我不会得到一个错误,但是,当我发送一个空值时,我得到一个ValidationError字段Required type=Missing Error.

例如,我可以做100,这是可行的,但它与使用class (Profile)的意义不符

from typing import Optional, Dict

class User(BaseModel):
    id: str
    username: str
    password: str
    connections: Optional[Connections]     <---- not working returning ValdiationError if null value sent
    profile: Optional[Profile]             <---- not working returning ValdiationError if null value sent

class Profile(BaseModel):
    id: str
    profile_id: str
    details: str
    

class Connections(BaseModel):
     connection_id: str
     connection_count: int
     connection_names: Dict[str, str]

我刚接触PYDNATIC的更新,所以如果有任何帮助,我将不胜感激!

推荐答案

您不必从自定义类迁移,您可以将默认值设置为None,并仍然使用您的模型:

from pydantic import BaseModel
from typing import Optional, Dict           

class Profile(BaseModel):
    id: str
    profile_id: str
    details: str
    

class Connections(BaseModel):
     connection_id: str
     connection_count: int
     connection_names: Dict[str, str]
        
class User(BaseModel):
    id: str
    username: str
    password: str
    connections: Optional[Connections] = None  
    profile: Optional[Profile] = None

我同意这是相当不幸的是,即使使用可选类型,如果没有缺省值也不能处理它,但我认为无论如何这都不是问题,也不是代码气味.

Python相关问答推荐

按照行主要蛇扫描顺序对点列表进行排序

Pandas 在最近的日期合并,考虑到破产

用Python解密Java加密文件

为什么sys.exit()不能与subproccess.run()或subprocess.call()一起使用

Julia CSV for Python中的等效性Pandas index_col参数

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

ThreadPoolExecutor和单个线程的超时

pandas:排序多级列

移动条情节旁边的半小提琴情节在海运

如何在表中添加重复的列?

在Python中,从给定范围内的数组中提取索引组列表的更有效方法

启动带有参数的Python NTFS会导致文件路径混乱

为什么\b在这个正则表达式中不解释为反斜杠

为什么if2/if3会提供两种不同的输出?

在matplotlib中使用不同大小的标记顶部添加批注

语法错误:文档. evaluate:表达式不是合法表达式

如何将返回引用的函数与pybind11绑定?

Python日志(log)库如何有效地获取lineno和funcName?

如何从一个维基页面中抓取和存储多个表格?