Validation in SQLAlchemy

pyramid, python, sqlalchemy

Solution

By empty fields I guess you mean an empty string rather than a NULL. A simple method is to add validation, e.g.:

class Article(Base):
    ...
    name = Column(Text, unique=True)
    ...

    @validates('name')
    def validate_name(self, key, value):
        assert value != ''
        return value

To implement it at a database level you could also use a check constraint, as long as the database supports it:

class Article(Base):
    ...
    name = Column(Text, CheckConstraint('name!=""')
    ...

Problem

How can I get the required validator in SQLAlchemy? Actually I just wanna be confident the user filled all required field in a form. I use PostgreSQL, but it doesn't make sense, since the tables created from Objects in my models.py file: ``` from sqlalchemy import ( Column, Integer, Text, DateTime, ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, ) from zope.sqlalchemy import ZopeTransactionExtension from pyramid.security import ( Allow, Everyone, ) Base = declarative_base() class Article(Base): """ The SQLAlchemy declarative model class for a Article object. """ __tablename__ = 'article' id = Column(Integer, primary_key=True) name = Column(Text, nullable=False, unique=True) url = Column(Text, nullable=False, unique=True) title = Column(Text) preview = Column(Text) content = Column(Text) cat_id = Column(Integer, nullable=False) views = Column(Integer) popular = Column(Integer) created = Column(DateTime) def __unicode__(self): return unicode(self.name) ``` So this `nullable=False` doesn't work, because the records added in any case with empty fields. I can of course set the restrictions at the database level by set name to NOT NULL for example. But there must be something about validation in SQLAlchemy isn't it? I came from yii php framework, there it's not the problem at all.

Original source