Sqlalchemy validator for two fields

SQLAlchemy docs explain how to use the @validates decorator to add model validation.

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 have a model with two dates, and I would like to create a validator that ensures that one date is always greater than the second. Is it possible to create a model level validator? If so, what is the syntax?

+6
source share
1 answer

Here is a small example for validators.

You can use CheckConstraint in your model declaration. Or you can use the @validates decorator. But this call 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

+8
source

Source: https://habr.com/ru/post/952888/


All Articles