Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy validator for two fields

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?

like image 680
danatron Avatar asked Aug 31 '13 18:08

danatron


1 Answers

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

like image 88
matrixise Avatar answered Sep 20 '22 01:09

matrixise