【问题标题】:Extend Marshmallow Schema but Override Field Required Property扩展 Marshmallow 架构但覆盖字段必需属性
【发布时间】:2020-12-24 23:31:50
【问题描述】:

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

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 inheritance marshmallow


    【解决方案1】:

    它可能不在文档中,因为这些只是 python 中的基本类继承规则。

    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

    通常最好先尝试一下,看看是否可以通过巧妙地声明字段来避免首先使用它们,但它会在你需要时出现。

    【讨论】:

      【解决方案2】:

      您正在寻找部分加载吗?

      跳过required=True验证

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

      【讨论】:

        猜你喜欢
        • 2012-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多