flask开发中设置Flask SQLAlchemy 的 db.Column 只存储非负整数(即 0 或正整数)

如果你想控制一个 Flask SQLAlchemy 的 db.Column 只存储非负整数(即 0 或正整数),你可以在模型中使用验证来确保这一点。一种常见的方法是使用模型的 validate 方法或者在执行插入或更新操作时进行检查。

以下是实现这一目标的几种方法:

方法 1:使用自定义验证

你可以重写模型的 __init__ 方法,或者在定义 setter 方法时加入验证:

python 复制代码
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class MyModel(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    non_negative_integer = db.Column(db.Integer, nullable=False, default=0)

    def __init__(self, non_negative_integer=0, *args, **kwargs):
        if non_negative_integer < 0:
            raise ValueError("non_negative_integer must be non-negative")
        self.non_negative_integer = non_negative_integer
        super().__init__(*args, **kwargs)

# 或者也可以定义一个 setter 方法
@property
def non_negative_integer(self):
    return self._non_negative_integer

@non_negative_integer.setter
def non_negative_integer(self, value):
    if value < 0:
        raise ValueError("non_negative_integer must be non-negative")
    self._non_negative_integer = value

方法 2:在数据插入或更新的时候检查

在每次插入或更新数据之前,可以进行检查:

python 复制代码
def create_model(non_negative_integer):
    if non_negative_integer < 0:
        raise ValueError("non_negative_integer must be non-negative")
    new_model = MyModel(non_negative_integer=non_negative_integer)
    db.session.add(new_model)
    db.session.commit()

方法 3:使用 SQLAlchemy 的检查约束

如果你使用 PostgreSQL 或支持 SQL 检查约束的数据库,可以在模型中添加一个另外的约束来限制负值:

python 复制代码
from sqlalchemy import CheckConstraint

class MyModel(db.Model):
    __tablename__ = 'my_model'
    id = db.Column(db.Integer, primary_key=True)
    non_negative_integer = db.Column(db.Integer, nullable=False, default=0)
    
    __table_args__ = (
        CheckConstraint('non_negative_integer >= 0', name='check_non_negative_integer'),
    )

以上方法可以帮助你确保 non_negative_integer 列只能存储非负整数。选择使用哪种方法取决于你的具体需求和项目结构。

相关推荐
李高钢14 小时前
Python Flask 框架入门:从零搭建你的第一个 Web 应用
前端·python·flask
半亩码田2 天前
【.NET新特性·第17篇】EF Core 10 与 Aspire 13.1
python·flask·.net
2601_962078033 天前
构建RESTful APIs:使用Python和Flask
python·flask·web开发·api设计·构建restfulapis
2601_962382433 天前
基于Flask构建的Doge风格备忘录Web应用:支持用户注册、任务分类与完成状态管理
flask·web应用·备忘录·用户认证·数据库集成
jsjzsl24 天前
独立自由度框架下位置自由度的本体论特征、物理现象与新技术路径
python·flask·fastapi
2601_962099085 天前
python flask sqlalchemy连接数据库流程介绍
数据库·python·flask·教程·sqlalchemy
烂蜻蜓5 天前
Flask入门教程(附录):模板渲染API——Jinja2集成全解析
后端·python·flask
千里码aicood5 天前
Flask-基于图神经网络的谣言检测研究
人工智能·神经网络·flask
烂蜻蜓6 天前
Flask入门教程(三十一):实用函数与类API——全局工具函数速查
后端·python·flask
千里码aicood6 天前
flask-基于注意力机制的异常流量检测与自动防御系统
后端·python·flask