Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

python - 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...