验证器不工作。NameError: name 'MinValueValidator' is not defined
最佳答案
您需要从 django.core.validators
模块导入 MinValueValidator
:
from django.core.validators import <b>MinValueValidator</b>
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=[<b>MinValueValidator(Decimal('0.01'))</b>]
)
def __str__(self):
return str(self.id)
请注意,验证不在数据库级别运行,也不在模型层执行(除非您自己触发这些,例如使用 my_product.full_clean()
).
自 django-2.2 , Django 有一个框架来指定数据库级别的约束。然而,这需要数据库支持检查约束(一些数据库会简单地忽略 CHECK
子句)。您可以通过以下方式指定:
from django.core.validators import <b>MinValueValidator</b>
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=[<b>MinValueValidator(Decimal('0.01'))</b>]
)
class Meta:
constraints = [
constraints.CheckConstraint(
<b>check=Q(price__gte=Decimal('0.01'))</b>,
name='price_positive'
)
]
def __str__(self):
return str(self.id)
关于django - 如何使用 Python 在 Django 中只有正十进制数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61350975/