Validation in SQLAlchemy

这一生的挚爱 提交于 2019-12-06 06:18:32

问题


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.


回答1:


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, nullable=False, 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!=""')
    ...


来源:https://stackoverflow.com/questions/20718469/validation-in-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!