【发布时间】:2020-02-19 12:27:01
【问题描述】:
在将可用项目列表保存到数据库之前,我需要检查模型字段。
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'})
为了验证,我在模型中添加了 clean 方法
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 ")
它有效,但我读到在保存方法中使用验证是不正确的。以及正确的使用方法——clean,为什么在我的情况下它不起作用?
【问题讨论】:
-
正确的方法确实是使用
clean(),但是模型上的clean()方法不会自动调用。当您清理模型的ModelForm(通过检查form.is_valid())或验证ModelSerializer时,它会被调用。您也可以自己调用它。创建Vendors对象,首先调用full_clean()(并捕获ValidationError),然后才调用save()。注意:如果你调用full_clean(),模型已经验证了国家设置是否正确,你不需要在clean()中添加。
标签: python django django-rest-framework