Flask validates decorator multiple fields simultaneously Flask validates decorator multiple fields simultaneously flask flask

Flask validates decorator multiple fields simultaneously


Order the fields in the order they were defined on the model. Then check if the last field is the one being validated. Otherwise just return the value unchecked. If the validator is validating one of the earlier fields, some of them will not be set yet.

@validates('field_one', 'field_two')def validates_fields(self, key, value):    if key == 'field_two':        assert self.field_one != value    return value

See this example.


Adding another answer here, as the accepted one didn't quite meet my use case for using another field to validate and modify relationship/collection fields, which are not really compatible with @validates. In this case you can use an event listener for the before_flush event to achieve what you're looking for:

@event.listens_for(Session, 'before_flush')def validate_and_modify_relationships(session, flush_context, instances):    """    Complex validation that cannot be performed with @valdiates    """        # new records only (for updates only, use session.dirty)    for instance in session.new:        if isinstance(instance, MyData):            if instance.some_other_value:                instance.some_relation = []

More details here: Flask-SQLAlchemy validation: prevent adding to relationship based on other field