Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用模型清理方法进行字段验证_Python_Django_Django Rest Framework - Fatal编程技术网

Python 使用模型清理方法进行字段验证

Python 使用模型清理方法进行字段验证,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

在将可用项保存到数据库之前,我需要检查model字段中的可用项列表

models.py

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方法的异常。我为此提出了一个新问题。谢谢你的帮助。