Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend Marshmallow Schema but Override Field Required Property

Noob question, but I have a simple schema:

class User(Schema):
    name = fields.Str(required=True)
    email = fields.Str(required=True)

And I want to extend it, but in the extended case make a field optional

class UserIHavePhoneNumberFor(User):
    phone = fields.Str(required=True)
    # Don't Care about Email because I can pester them via phone!

I've checked the docs but can't find a way to do this. Any help?

Thank you!

like image 994
Nathaniel Rink Avatar asked Oct 28 '25 15:10

Nathaniel Rink


1 Answers

It's probably not in the docs because these are just basic class inheritance rules in python.

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

If you need more complex rules than that, you can always just write your own custom validation rules:

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

or even:

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

It's usually best to try and see if you can avoid using those first by being smart about declaring your fields, but it's there when you need it.

like image 162
Stephen Fuhry Avatar answered Oct 30 '25 06:10

Stephen Fuhry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!