当验证器以这种方式编写时,我的参数有问题:
cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias])
它会自动获取validator.py中相应字段的值
def insumo_existencias(value):
#Por alguna razon, me esta devolviendo un string
insumo = models.Insumo.objects.get(id=1)
if (insumo.cantidadexistencias < value):
raise ValidationError(
_('Error no hay existencias suficientes'),
)
所以,我只需将其称为值即可,但是当我想传递另一个参数时,该函数不再获取该字段的值。我试过这个:
cantidadusada = models.DecimalField(max_digits=50, decimal_places=3,validators=[insumo_existencias(cantidadusada,idinsumo)])
它不起作用。 显然,验证器函数已更改为接受参数
您可以在保存功能中更改它:
def save(self,*args, **kwargs):
if (insumo.cantidadexistencias > value):
super().save(*args, **kwargs)
else:
pass
#do not save it!and raise error
您可以通过创建自定义验证器函数或类来将多个参数传递给验证器。
使用函数
from django.core.exceptions import ValidationError
def custom_validator(value, param1, param2):
if not some_condition(value, param1, param2):
raise ValidationError(f'{value} failed the validation with {param1} and {param2}')
由于 Django 验证器仅接受单个参数 (
value
),因此您需要使用 lambda 或部分函数来传递其他参数:
from functools import partial
class MyModel(models.Model):
my_field = models.CharField(max_length=100, validators=[partial(custom_validator, param1='value1', param2='value2')])