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

相关推荐
lilye662 小时前
程序化广告行业(44/89):岗位职责与RTB竞价逻辑深度解析
大数据·elasticsearch·flask·memcache
带娃的IT创业者2 小时前
《Python Web部署应知应会》No2:如何基于FastAPI 和 OLLAMA 架构实现高并发 AI 推理服务
python·架构·flask·fastapi
网络风云9 小时前
Flask(六)数据库与模型操作
数据库·python·flask
Learn-Share_HY12 小时前
[Python]如何利用Flask搭建一個Web服務器,並透過Ngrok訪問來實現LINE Bot功能?
linux·人工智能·python·ubuntu·flask·ollama·ngrok
清风序来1 天前
为什么使用Flask + uWSGI + Nginx 部署服务?
python·nginx·flask
百锦再1 天前
Reactive编程:应用场景和传统比较
运维·开发语言·javascript·python·flask·react·tornado
清风序来1 天前
Flask项目部署:Flask + uWSGI + Nginx
python·flask
海绵波波1071 天前
【源码阅读/Vue & Flask前后端】简历数据查询功能
前端·vue.js·flask
带娃的IT创业者1 天前
《Python Web网站部署应知应会》No4:基于Flask的调用AI大模型的高性能博客网站的设计思路和实战(上)
前端·python·flask
vener_2 天前
基于Flask的通用登录注册模块,并代理跳转到目标网址
后端·python·flask