MinValueValidator在Django中的DecimalField上不起作用 [英] MinValueValidator not working on DecimalField in Django

查看:50
本文介绍了MinValueValidator在Django中的DecimalField上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用Django和Django Rest Framework开发的API。我有一个带有DecimalField的模型,该模型应存储至少一个值。因此,我以以下方式定义了该字段:

I have an API developed with Django and Django Rest Framework. I've got a model with a DecimalField which should store values of at least one. Therefore, I've defined the field in the following way:

goal = models.DecimalField(decimal_places=2, max_digits=16, validators=[MinValueValidator(1)])

当我创建调用API的对象时(使用DRF的ModelViewSet ),我可以创建带有负目标的对象,因此验证器似乎不起作用(我将其包含在模型序列化器中)。

When I create objects calling the API (using DRF's ModelViewSet), I can create objects with negative "goal", so the validator doesn't seem to work (I've got it included in the model serializer).

任何

推荐答案

from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _


class MyModel(models.Model):
    goal = models.DecimalField(decimal_places=2, max_digits=16, 
              validators=[MinValueValidator(1)])

    def clean(self):
        if self.goal < 1:
            raise ValidationError(_('Only numbers equal to 1 or greater are accepted.'))

这篇关于MinValueValidator在Django中的DecimalField上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆