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

相关推荐
BuLingLings2 小时前
vue3+flask+sqlite前后端项目实战
python·sqlite·flask
wxl7812271 天前
基于flask+pandas+csv的报表实现
python·flask·pandas
西红柿土豆丶1 天前
基于Flask、Bootstrap及深度学习的水库智能监测分析平台
人工智能·python·深度学习·flask·bootstrap
带娃的IT创业者1 天前
《AI大模型应知应会100篇》第58篇:Semantic Kernel:微软的大模型应用框架
人工智能·microsoft·flask
未名编程1 天前
【Flask开发踩坑实录】pip 安装报错:“No matching distribution found” 的根本原因及解决方案!
python·flask·pip
兆。2 天前
电子商城后台管理平台-Flask Vue项目开发
前端·vue.js·后端·python·flask
-曾牛2 天前
Azure OpenAI 聊天功能全解析:Java 开发者指南
java·开发语言·人工智能·spring·flask·azure·大模型应用
小屁孩大帅-杨一凡2 天前
Azure Document Intelligence
后端·python·microsoft·flask·azure
Q_Q19632884753 天前
python小区物业管理系统-小区物业报修系统
开发语言·spring boot·python·django·flask·node.js·php
万能程序员-传康Kk3 天前
食物数据分析系统vue+flask
前端·vue.js·flask