扩展 Marshmallow 模式但覆盖必需的字段 属性

Extend Marshmallow Schema but Override Field Required Property

菜鸟问题,但我有一个简单的架构:

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 继承规则。

class UserIHavePhoneNumberFor(User):
    phone = fields.Str(required=True)
    email = fields.Str(required=False)

如果您需要比这更复杂的规则,您始终可以编写自己的自定义验证规则:

https://marshmallow.readthedocs.io/en/stable/extending.html#raising-errors-in-pre-post-processor-methods

甚至:

https://marshmallow.readthedocs.io/en/stable/extending.html#schema-level-validation

通常最好尝试看看是否可以通过明智地声明字段来避免首先使用它们,但它在您需要时就在那里。

您要找的是部分加载吗?

跳过required=True验证

https://marshmallow.readthedocs.io/en/stable/quickstart.html#partial-loading