首页 > 解决方案 > 扩展 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!

我已经检查了文档,但找不到这样做的方法。有什么帮助吗?

谢谢!

标签: pythoninheritancemarshmallow

解决方案


它可能不在文档中,因为这些只是 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

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


推荐阅读