SQLAlchemy: What is the difference beetween CheckConstraint and @validates
<p>In a SQLAlchemy model what is the difference between adding a CheckConstraint and adding a @validates decorated validation method? Is the one acting on the database level and the other one not? And are there any guidelines when to use which?</p>

<p>Specifically, what is the difference between using</p>

<pre><code>__table_args__ = (CheckConstraint('to_node_id != from_node_id'), )
</code></pre>

<p>and</p>

<pre><code>@validates('from_node', 'to_node')
def validate_nodes_are_different(self, key, field):
    if key == 'to_node' and field and field is self.from_node:
            raise ValueError
    elif key == 'from_node' and field and field is self.to_node:
            raise ValueError
    return field
</code></pre>

<p><code>CheckConstraint</code> is a database-level check; <code>@validates</code> is a Python-level check. A database-level check is more universal; the constraint is satisfied even if you access the database through other means. A Python-level check is more expressive; you can usually check for complicated constraints more easily.</p>

<p>The other thing you should consider is what happens when you want to change the constraint. A <code>CHECK</code> constraint will force you to change existing data to conform when you change the constraint. A Python-level constraint allows you to force only new data to conform to the constraint.</p>

python sqlalchemy