Skip to content

decorator validates add order parameter#1720

Closed
ficapy wants to merge 1 commit intomarshmallow-code:devfrom
ficapy:validates_order
Closed

decorator validates add order parameter#1720
ficapy wants to merge 1 commit intomarshmallow-code:devfrom
ficapy:validates_order

Conversation

@ficapy
Copy link
Copy Markdown

@ficapy ficapy commented Jan 15, 2021

This allows validate to be executed in order

For example, if field A needs to query the database when validating, and field B relies on the results of field A's query,
then validation function A needs to query the database and validation function B needs to query the database if there is no guarantee that A will be executed first.
Or merge validation functions A, B together, or some other very ugly solution

Adding the order parameter would look like this

class User(Schema):
    name = fields.Str()
    age = fields.Int()
    sex = fields.Int()

    @validates("name", order=1)
    def validate_name(self, value):
        self.context["order"] += "1"
        return value

    @validates("age", order=2)
    def validate_age(self, value):
        self.context["order"] += "2"
        return value

    @validates("sex")
    def validate_sex(self, value):
        self.context["order"] += "0"
        return value

schema = User()
schema.context["order"] = ""
schema.load({"name": "name", "age": 24, "sex": 1})
assert schema.context["order"] == "210"

@sloria
Copy link
Copy Markdown
Member

sloria commented Feb 16, 2021

Thanks for the PR. This was also added in #600 but there's still discussion needed on whether this is something we want to add to core. Let's continue discussion on that PR.

@sloria sloria closed this Feb 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants