【问题标题】:Django Rest Framework model serializer with out unique together validation没有唯一一起验证的 Django Rest Framework 模型序列化程序
【发布时间】:2018-02-10 10:52:56
【问题描述】:

我有一个带有一些字段的模型和一个unique together

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

显然,通过这种方式,关于 Django REST 框架序列化程序,当我尝试使用相同的 device_identifierdevice_platform 进行 PUT 时出现错误(如果已经存在包含此数据的条目)。

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

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

【问题讨论】:

    标签: django python-2.7 serialization django-rest-framework unique


    【解决方案1】:

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

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

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

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

    【讨论】:

      【解决方案2】:

      您需要从序列化程序的列表中删除验证器。

      虽然不完全一样,但步骤说明here

      【讨论】:

        猜你喜欢
        • 2016-11-21
        • 2023-03-18
        • 2020-05-23
        • 2020-12-26
        • 2018-07-06
        • 1970-01-01
        • 2016-11-29
        • 2021-03-09
        • 2013-11-27
        相关资源
        最近更新 更多