Django Rest Framework模型序列化器,没有唯一的共同验证 [英] Django Rest Framework model serializer with out unique together validation

查看:168
本文介绍了Django Rest Framework模型序列化器,没有唯一的共同验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型,其中包含一些字段和唯一的

I have a model with some fields and a unique together:

....
class Meta(object):
    unique_together = ('device_identifier', 'device_platform',)

显然,以这种方式,关于Django rest框架序列化程序,当我尝试使用相同的 device_identifier 和 device_platform (如果已经存在包含此数据的条目)。

Obviously, in this way, about Django rest framework serializer, I obtain an error when I try to make a PUT with the same device_identifier and device_platform (if already exist an entry with this data).

{
  "non_field_errors": [
    "The fields device_identifier, device_platform must make a unique set."
  ]
}

是否可以在模型序列化器中禁用此验证?
因为我需要在保存模型步骤中处理这种情况(对我来说,在序列化程序验证中这不是错误)

Is possible to disable this validation in my model serializer? Because I need to manage this situation during save model step (for me, in serializer validation this is not an error)

推荐答案

Django REST框架在序列化器上应用 UniqueTogetherValidator 。您可以通过覆盖序列化程序定义中的 validators 字段来删除它。

Django REST framework applies the UniqueTogetherValidator on the serializer. You can remove this by override the validators field in the serializer definition.

class ExampleSerializer(serializers.ModelSerializer):
    class Meta:
        validators = []

请注意,这还会删除其他唯一检查验证器应用于模型,可能不是最好的主意。为避免这种情况,只需在序列化程序上覆盖 get_unique_together_validators 方法,以确保仅删除唯一检查。

Note that this also removes the other unique-check validators that are applied on the model, which might not be the best idea. To avoid that, just override the get_unique_together_validators method on the serializer, to ensure only unique-together check is removed.

class ExampleSerializer(serializers.ModelSerializer):
    def get_unique_together_validators(self):
        """Overriding method to disable unique together checks"""
        return []

这篇关于Django Rest Framework模型序列化器,没有唯一的共同验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆