Validation in SQLAlchemy

How can I get the required validator in SQLAlchemy? In fact, I just want to be sure that the user has filled out all the required field in the form. I use PostgreSQL, but this does not make sense, since the tables created from the objects in my models.py file are:

 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=Falsedoes not work because records are added anyway with empty fields. I can, of course, set restrictions at the database level, for example, using the NOT NULL set name. But in SQLAlchemy there should be something like validation, isn't it? I came from yii php framework, there is no problem there.

+4
source share
1 answer

, , , NULL. A , :

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

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

, check, :

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

All Articles