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

相关推荐
2601_9498477511 小时前
Cookie 跨端三方库仓颉适配全流程
python·django·flask
tryCbest4 天前
Python之Flask项目部署到阿里云
python·阿里云·flask
心运软件5 天前
Fashion-MNIST 图像分类实战:TensorFlow 五模型对比与 Flask 可视化
分类·flask·tensorflow
编码者卢布6 天前
【Azure Storage Account】Azure Queue指标中的Transactions 高,真实业务处理的消息就多吗?
microsoft·flask·azure
winfredzhang8 天前
从零实现“照片按地理位置显示在矢量地图上”:Flask + SQLite + Leaflet 全栈实战
python·sqlite·flask
龙腾AI白云10 天前
数字孪生、具身智能、世界模型三者交叉
数据库·人工智能·机器学习·flask·pygame
hhb_61811 天前
Flask+SQLite实现用户管理接口
python·sqlite·flask
QQ142207844912 天前
基于 Flask 的「自动任务控制台」设计与踩坑实录
后端·python·flask
深圳市尚想信息技术有限公司13 天前
TM52F1376海速芯HITENX Flash-8位MCU单片机,多通道ADC + 段码显示一体化主控芯片
单片机·嵌入式硬件·mcu·flask·芯片·控制器
高级程序源14 天前
django校园寻物通失物招领平台32261-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·django·flask·课程设计