SQLAlchemy 中的验证 [英] Validation in SQLAlchemy

查看:79
本文介绍了SQLAlchemy 中的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 SQLAlchemy 中获取所需的验证器?实际上,我只是想确信用户在表单中填写了所有必填字段.我使用 PostgreSQL,但它没有意义,因为在我的 models.py 文件中从对象创建的表:

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)

所以这个 nullable=False 不起作用,因为在任何情况下添加的记录都带有空字段.例如,我当然可以通过将 name 设置为 NOT NULL 在数据库级别设置限制.但是在 SQLAlchemy 中一定有一些关于验证的东西,不是吗?我来自 yii php 框架,这根本不是问题.

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.

推荐答案

我猜你说的空字段是指空字符串而不是 NULL.简单方法是添加验证,例如:

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

这篇关于SQLAlchemy 中的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆