首页 > 解决方案 > 如何使用 Python 在 Django 中只有正十进制数?

问题描述

验证器不工作。NameError:名称“MinValueValidator”未定义

标签: djangopython-3.x

解决方案


您需要从模块中导入, :MinValueValidatordjango.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 有一个框架来指定数据库级别的约束。然而,这要求数据库支持检查约束(一些数据库只是忽略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)

推荐阅读