【发布时间】:2015-12-10 23:00:32
【问题描述】:
我有一个带有自定义验证代码的 django 模型。当我使用 django-rest-framework 尝试创建/更新模型时,验证代码确实会运行,但不是输出一些带有错误内容的 JSON,而是失败并带有 ValidationError。为什么 django-rest-framework 没有捕捉到这个错误?
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')
当我尝试发布 type="d" 的 JSON 数据时,我正确地得到以下响应:{ "type": ["this is not one of the valid choices"]}。
但是当我尝试在 default=true 的情况下 POST JSON 数据(并且数据库中已经存在相同类型的默认模型)时,我只是得到了 ValidationError 而不是格式良好的 JSON。
【问题讨论】:
标签: django django-models django-rest-framework