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

相关推荐
liuyicenysabel13 小时前
Flask 个人站 iProfile 上线笔记(k3s + Nginx + Let‘s Encrypt)
笔记·nginx·flask
johnny2331 天前
Flask生态:Flask-SocketIO、Flask-MonitoringDashboard
flask
weixin_BYSJ19872 天前
springboot智慧公共交通系统---附源码51123
java·javascript·spring boot·python·django·flask·php
0xBADCODE2 天前
Flask SSTI读SECRET_KEY+伪造Session:税务系统渗透全流程
前端·后端·python·安全·web安全·网络安全·flask
weixin_BYSJ19873 天前
springboot游戏账号租赁系统---附源码50345
java·spring boot·python·游戏·django·flask·php
编码者卢布4 天前
【Azure Key Vault】资源组被误删后,如何恢复 Azure Key Vault?
microsoft·flask·azure
weixin_BYSJ19875 天前
springboot小区物业管理小程序---附源码45555
java·javascript·spring boot·python·django·flask·php
qq_22589174665 天前
基于Flask的空气质量监测与预测分析系统
开发语言·后端·python·信息可视化·django·flask
梅孔立5 天前
Docker 部署 Python3\.11 Flask爬虫项目 终极稳定教程(解决线程报错/挂载失效/pip报错)
爬虫·docker·flask
树码小子7 天前
Python 超轻量 Web 框架 Flask 快速入门教程
前端·python·flask