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

相关推荐
百锦再5 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
QQ5110082855 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
QQ_19632884755 天前
Python-flask框架西山区家政服务评价系统网站设计与开发-Pycharm django
python·pycharm·flask
计算机专业码农一枚5 天前
Python-flask框架基于推荐算法的在线课程推荐系统设计与实现-Pycharm django
python·flask·推荐算法
NGINX开源社区5 天前
使用 Microsoft Entra ID 配置 NGINX Plus 以实现 SAML SSO
后端·python·flask
山岚的运维笔记6 天前
SQL Server笔记 -- 第86章:查询存储
笔记·python·sql·microsoft·sqlserver·flask
先做个垃圾出来………7 天前
Django vs Flask 异步视图性能对比:数据驱动的深度分析
数据库·django·flask
迪巴拉15257 天前
基于Yolov8训练的Flask后端和Uniapp野生菌识别系统
yolo·flask·uni-app
麦麦大数据8 天前
M004_基于Langchain+RAG的银行智能客服系统设计与开发
typescript·langchain·flask·vue3·faiss·rag
夜瞬8 天前
【Flask 框架学习】01:编写第一个 Flask 应用
后端·python·学习·flask