我已经制作了一个api,客户在该api上通过发布请求发送他/她的付款详细信息,因此需要在模型级别验证这些数据。我如何通过将模型字段与其他模型字段进行比较来验证模型字段。例如:
models.py
Orders(models.Model):
amount = models.DecimalField(max_digits=19, decimal_places=4)
currency = models.CharField(max_length=3,choices=[('INR','INR')]) more choices are to be added
payee_pan = models.CharField(max_length=10)
需要验证:如果货币为"INR"且金额大于50000,则必须存在payee_pan。为了验证它,我使用model.full_clean((,同时将模型对象保存在views.py 中
views.py
try:
orders.full_clean()
except ValidationError:
return Response({"Error message":"invalid request body"})
else:
orders.save()
我真的很感激有人能帮我,因为我在这一点上坚持了这么久。enter code here
from django.db import models
from django.core.exceptions import ValidationError
class Orders(models.Model):
amount = models.DecimalField(max_digits=19, decimal_places=4)
currency = models.CharField(max_length=3, choices=[('INR','INR')]) # more choices are to be added
payee_pan = models.CharField(max_length=10)
class Meta:
verbose_name = "Order"
verbose_name_plural = "Orders"
def clean(self):
if self.currency == 'INR' and self.amount > 50000 and not self.payee_pan:
raise ValidationError(
{"payee_pan": "Payee Pan field is required"}
)
def save(self, *args, **kwargs):
self.full_clean()
return super().save(*args, **kwargs)
您可以删除视图中的try-except块。调用save((方法将调用引擎盖下的full_clean((方法,该方法将调用任何验证挂钩。
您可以通过覆盖模型上的clean
方法来执行此类验证(参考验证对象[Django-docs](:
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
class Orders(models.Model):
amount = models.DecimalField(max_digits=19, decimal_places=4)
currency = models.CharField(max_length=3,choices=[('INR','INR')])
payee_pan = models.CharField(max_length=10)
def clean(self):
if self.currency == 'INR' and self.amount > 50000 and not self.payee_pan:
raise ValidationError(_('Payee Pan is required'))
注意:理想情况下,模型名称应该是单数(如果检查模型的详细名称复数,则最终为
Orderss
当前具有额外的s
(。因此,它应该是Order
,而不是。Orders