The SQLAlchemy docs explain how to use a @validates decorator to add validation to a model.
from sqlalchemy.orm import validates
class EmailAddress(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
email = Column(String)
@validates('email')
def validate_email(self, key, address):
assert '@' in address
return address
I've got a model with two dates, and I'd like to create a validator ensuring one date is always greater than the second. Is it possible to create a model level validator? If so what is the syntax?
Here is a small example for the validators.
You can use the CheckConstraint in the declaration of your model. Or you can use the @validates decorator. But this one will be called by SQLAlchemy for each name in the first arguments.
@validates('started_at', 'stopped_at')
def do_validation(self, key, field):
return field
Please, check this code: https://gist.github.com/matrixise/6417293
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With