Python 使用模型清理方法进行字段验证
在将可用项保存到数据库之前,我需要检查model字段中的可用项列表 models.pyPython 使用模型清理方法进行字段验证,python,django,django-rest-framework,Python,Django,Django Rest Framework,在将可用项保存到数据库之前,我需要检查model字段中的可用项列表 models.py class Vendors(models.Model): COUNTRY_CHOICES = tuple(countries) ... country = models.CharField(max_length=45, choices=COUNTRY_CHOICES) ... 用于保存模型的类 class CsvToDatabase(APIView): def po
class Vendors(models.Model):
COUNTRY_CHOICES = tuple(countries)
...
country = models.CharField(max_length=45, choices=COUNTRY_CHOICES)
...
用于保存模型的类
class CsvToDatabase(APIView):
def post(self, request, format=None):
data = request.data
for key, vendor in data.items():
Vendors(
...,
country=vendor['Country'],
...,
).save()
return Response({'received data': request.data,
'message': 'Vendors from vendors_list were successfully added to the database'})
为进行验证,在模型中添加了清洁方法
def clean(self):
if self.country not in [x[1] for x in countries]:
raise ValidationError(detail="Country name does not match to the country list ")
但它不起作用
下一步,我将相同的代码添加到方法save
def save(self):
if self.country not in [x[1] for x in countries]:
raise ValidationError(detail="Country name does not match to the country list ")
它是有效的,但我读到在save方法中使用验证是不正确的。正确的使用方法-清洁,为什么在我的情况下它不起作用?有关验证模型如何工作的完整说明,请参阅
简而言之:要验证一个对象,需要对该对象调用full\u clean()
。这不是自动发生的!它发生在以下情况:
- 使用
并在表单上调用ModelForm
is\u valid()
- 在DRF中使用
,并在序列化程序上调用ModelSerializer
is\u valid()
- 您可以显式调用
full\u clean()
full\u clean()
,然后调用save()
。注意:您甚至不必添加自己的检查(clean()
方法),因为Django会在clean_fields()
期间自动执行有效选项的检查,而choices
是在字段上设置的:
v = Vendors(country=vendor['country'], ...)
try:
v.full_clean()
except ValidationError as e:
# do something e.g. return error response
v.save()
return Response(...)
正确的方法确实是使用
clean()
,但是不会自动调用模型上的clean()
方法。当您为模型清理模型表单
时(通过检查表单.is\u valid()
)或当您验证模型序列化程序
时,会调用它。你也可以自己叫它。创建Vendors
对象,首先调用full\u clean()
(并捕获验证错误),然后调用save()
。注意:如果您调用full\u clean()
,模型将验证国家/地区设置是否正确,您无需在clean()
中添加该选项。太好了,它可以工作,对我来说是非常有用的信息。对我来说还有一件事——如何捕捉异常?现在我有一个来自clean model方法的异常,我想使用一个来自POST class方法的异常。我为此提出了一个新问题。谢谢你的帮助。