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 列只能存储非负整数。选择使用哪种方法取决于你的具体需求和项目结构。

相关推荐
沈浩(种子思维作者)1 天前
系统要活起来就必须开放包容去中心化
人工智能·python·flask·量子计算
B站_计算机毕业设计之家1 天前
豆瓣电影数据采集分析推荐系统 | Python Vue Flask框架 LSTM Echarts多技术融合开发 毕业设计源码 计算机
vue.js·python·机器学习·flask·echarts·lstm·推荐算法
玄同7651 天前
Python 后端三剑客:FastAPI/Flask/Django 对比与 LLM 开发选型指南
人工智能·python·机器学习·自然语言处理·django·flask·fastapi
乔江seven2 天前
【Flask 进阶】3 从同步到异步:基于 Redis 任务队列解决 API 高并发与长耗时任务阻塞
redis·python·flask
云和数据.ChenGuang2 天前
python 面向对象基础入门
开发语言·前端·python·django·flask
Leinwin3 天前
Moltbot 部署至 Azure Web App 完整指南:从本地到云端的安全高效跃迁
后端·python·flask
2401_841495643 天前
【Web开发】基于Flask搭建简单的应用网站
后端·python·flask·视图函数·应用实例·路由装饰器·调试模式
极客小云3 天前
【基于AI的自动商品试用系统:不仅仅是虚拟试衣!】
javascript·python·django·flask·github·pyqt·fastapi
Andy Dennis3 天前
StreamFlow Player——局域网视频浏览中心
flask·传媒·pocket3
码界奇点4 天前
基于Flask与OpenSSL的自签证书管理系统设计与实现
后端·python·flask·毕业设计·飞书·源代码管理