验证django-rest-framework中的模型

时间:2015-09-14 20:26:55

标签: django django-models django-rest-framework

我有一个带有自定义验证码的django模型。当我使用django-rest-framework来尝试创建/更新模型时,验证代码确实会运行,而不是输出一些带有Validation错误的JSON w /错误内容。为什么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')

当我尝试在类型=" d"中发布JSON数据时,我正确地得到以下响应:{ "type": ["this is not one of the valid choices"]}

但是当我尝试在默认值为true的情况下POST JSON数据时(并且db中已经有相同类型的默认模型),我只是提出了ValidationError而不是格式化的JSON。

1 个答案:

答案 0 :(得分:1)

第一个验证错误有效,因为DRF会引发错误。

在框架内只引发了DRF的子类APIException。因此,您需要使用它的APIException类来引发错误。

例如,

from rest_framework.exceptions import APIException

class CustomException(APIException):

    status_code = 400
    default_detail = 'There can be only one default model per type.'

然后你可以在你的模型中做到这一点。

 if other_models.count() != 0:
        raise CustomException()

旁注您为什么要尝试使用代码在模型上创建unique together约束?您应该使用unique_together作为数据库级别执行此操作。

例如,在模型上你可以做这样的事情......

  class Meta:
        unique_together = ("is_default", "type")

运行迁移后,它们会在一起时将它们视为唯一!