在django-rest-framework中验证模型 [英] validating a model in django-rest-framework
问题描述
models.py
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $$ a,a),(b,b),(c,c)]
def clean(self,* args,** kwargs) b $ b#每个类型只能有一个默认模型
如果self.is_default:
other_models = MyModel.objects.filter(
type = self.type,
default = True).exclude(pk = self.pk)
如果other_models.count()!= 0:
raise ValidationError({default:每种类型只能有一个默认模型。 )
super(MyModel,self).clean(* args,** kwargs)
serializers.py
class MyModelSerializer(ModelSerializer):
class Meta:
model = MyModel
fields =('id','default','type')
当我尝试发送类型=d的JSON数据时,我正确地得到以下响应: {type:[this不是有效的选择之一]}
。
但是当我尝试POST JSON数据时,其中default = true(并且已经有db中的相同类型的默认模型),我只是得到ValidationError而不是格式良好的JSON。
首先验证错误的作用是因为DRF引发了它。
框架内仅引发了DRF子集 APIException
。所以你需要使用它的 APIException
类来引发错误。
例如,
from rest_framework.exceptions import APIException
class CustomException(APIException):
status_code = 400
default_detail ='每种类型只能有一个默认模型'
然后您可以在模型中执行此操作。
如果other_models.count()!= 0:
raise CustomException()
在侧边笔记中,为什么要尝试使用代码在模型上创建一个独一无二的约束?您应该使用 unique_together 作为数据库级别
例如,在模型上,你可以这样做...
code> class Meta:
unique_together =(is_default,type)
一旦你运行迁移,它会在一起考虑它们是唯一的!
I have a django model w/ custom validation code. When I use django-rest-framework to try and create/update the model, the validation code does get run, but rather than output some JSON w/ error content it fails w/ a ValidationError. Why doesn't django-rest-framework catch that error?
models.py
class MyModel(models.Model):
is_default = models.BooleanField()
type = models.CharField(max_length=64, choices=[("a","a"), ("b","b"), ("c","c")]
def clean(self, *args, **kwargs):
# there can be only 1 "default" model per type
if self.is_default:
other_models = MyModel.objects.filter(
type=self.type,
default=True).exclude(pk=self.pk)
if other_models.count() != 0:
raise ValidationError({"default": "There can be only one default model per type.")
super(MyModel, self).clean(*args, **kwargs)
serializers.py
class MyModelSerializer(ModelSerializer):
class Meta:
model = MyModel
fields = ('id', 'default', 'type')
When I try to POST JSON data where type="d", I correctly get the following response: { "type": ["this is not one of the valid choices"]}
.
But when I try to POST JSON data where default=true (and there are already default models of the same type in the db), I just get the ValidationError raised instead of the nicely formatted JSON.
The first validation error works because DRFs raises it.
Only subclasses of DRFs own APIException
are raised inside the framework. So you need to used it's APIException
class to rise the error.
For example,
from rest_framework.exceptions import APIException
class CustomException(APIException):
status_code = 400
default_detail = 'There can be only one default model per type.'
Then you could do this in your model.
if other_models.count() != 0:
raise CustomException()
On a side note why are you are trying to create a unique together
constraint on the model using code? You should do this as the database level using unique_together.
For example, on the model you could do something like this...
class Meta:
unique_together = ("is_default", "type")
Once you have run migrations it will consider them unique when together!
这篇关于在django-rest-framework中验证模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!