python - 扩展 Marshmallow 架构但覆盖字段必需属性
问题描述
菜鸟问题,但我有一个简单的架构:
class User(Schema):
name = fields.Str(required=True)
email = fields.Str(required=True)
我想扩展它,但在扩展的情况下,使一个字段可选
class UserIHavePhoneNumberFor(User):
phone = fields.Str(required=True)
# Don't Care about Email because I can pester them via phone!
我已经检查了文档,但找不到这样做的方法。有什么帮助吗?
谢谢!
解决方案
它可能不在文档中,因为这些只是 python 中的基本类继承规则。
class UserIHavePhoneNumberFor(User):
phone = fields.Str(required=True)
email = fields.Str(required=False)
如果您需要比这更复杂的规则,您可以随时编写自己的自定义验证规则:
甚至:
https://marshmallow.readthedocs.io/en/stable/extending.html#schema-level-validation
通常最好尝试看看是否可以通过聪明地声明字段来避免首先使用它们,但是当你需要它时它就在那里。
推荐阅读
- apache-nifi - 如何在Nifi的每个Flowfile中迭代json?
- visual-studio-2015 - 如何阅读“带有代码修复的分析器”项目的任何文件?
- c# - 无法从其他游戏对象的脚本中获取变量
- c++ - 在 C++ 中使用输出参数有什么优势吗?
- apache - Apache Ant build.xml:编译失败;有关详细信息,请参阅编译器错误输出
- regex - 查找和替换键:值对
- c# - 为什么在实体中添加具有自己 ID 的集合时,我总是得到主体 ID 而不是集合的 ID?
- python - Python3:使用 Python 连接到 postgresql 数据库...如何让结果查询作为 pandas 数据框中的行返回?
- sql - 如何创建可以在单个 SQL 子查询中引用先前数据条目的 SQL 层次结构
- c# - 如何在 Azure Cosmos DB Mongo API 中添加权重作为创建索引的一部分