django - 如何使用 Python 在 Django 中只有正十进制数?
问题描述
验证器不工作。NameError:名称“MinValueValidator”未定义
解决方案
您需要从模块中导入, :MinValueValidator
django.core.validators
from django.core.validators import MinValueValidator
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=4096)
price = models.DecimalField(
max_digits=15,
decimal_places=2,
validators=[MinValueValidator(Decimal('0.01'))]
)
def __str__(self):
return str(self.id)
请注意,验证不会在数据库级别运行,也不会在模型层执行(除非您自己触发这些,例如使用my_product.full_clean()
)。
从django-2.2开始,Django 有一个框架来指定数据库级别的约束。然而,这要求数据库支持检查约束(一些数据库只是忽略CHECK
子句)。您可以通过以下方式指定:
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models import Q
from django.db.models import constraints
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.CharField(max_length=4096)
price = models.DecimalField(
max_digits=15,
decimal_places=2,
validators=[MinValueValidator(Decimal('0.01'))]
)
class Meta:
constraints = [
constraints.CheckConstraint(
check=Q(price__gte=Decimal('0.01')),
name='price_positive'
)
]
def __str__(self):
return str(self.id)
推荐阅读
- java - 为什么我的链接到 Jar 的文件可以在 VS 代码中工作,但不能在终端中工作
- list - 如何在 for 循环中创建 dict?Python
- python - 为什么我在从文本文件导入列表的字符串中得到 \\n?
- api - 如何使用他们的 API 获取 Linkedin 个人资料数据?
- google-drive-shared-drive - 如何通过gshell软件访问共享驱动器?
- firebase - Flutter FCM 推送通知 - 前台通知点击事件
- swift - 为什么模拟响应无法解码?
- r - Need help on how to sort a tibble column by keyword in R
- firebase - Cant login using phone authentication in IOS - Flutter
- typescript - 让在 Promise 构造函数中分配的变量被 Typescript 标记为未定义