Django REST框架:序列化程序上的Unique_together验证 [英] Django REST Framework: Unique_together validation on Serializers

查看:81
本文介绍了Django REST框架:序列化程序上的Unique_together验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果序列化程序实例未能通过<$ c $,则 serializer.is_valid()返回 True 时会出现问题c>在模型方面的约束。

Having issues with a serializer.is_valid() returning True if the serializer instance fails a unique_together constraint on the model side.

有没有办法让我在序列化程序中指定强制执行 unique_together 约束?

Is there a way for me to specify in the serializer to enforce a unique_together constraint?

推荐答案

不幸的是,安德里亚斯的答案并不完整,因为它行不通

Unfortunately, Andreas's answer is not quite complete, as it will not work in the case of an update.

相反,您会想要更多类似的东西:

Instead, you would want something more like:

def validate(self, attrs):
    field1 = attrs.get('field1', self.object.field1)
    field2 = attrs.get('field2', self.object.field2)

    try:
        obj = Model.objects.get(field1=field1, field2=field2)
    except StateWithholdingForm.DoesNotExist:
        return attrs
    if self.object and obj.id == self.object.id:
        return attrs
    else:
        raise serializers.ValidationError('field1 with field2 already exists')

这将适用于PUT,PATCH和POST。

This will work for PUT, PATCH, and POST.

这篇关于Django REST框架:序列化程序上的Unique_together验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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