使用Django Rest Framework中的嵌套序列化程序进行串行器字段验证

时间:2016-08-04 12:26:34

标签: python django validation django-rest-framework serializer

我的模型ManagerUser有一个ForeignKey。 要更新发件人,我会发送PATCH方法,其中包含{"user": {"first_name": "John", "last_name": "Doe", "email": "john@doe.com"}

等嵌套对象
class CompanyManagerMeSerializer(serializers.ModelSerializer):
    user = UserMeSerializer()
    company = CompanyFullSerializer()

    def update(self, instance, validated_data):
        user_data = validated_data.pop('user', {})
        user = instance.user
        for key, val in user_data.items():
            setattr(user, key, val)
        user.save()

        company_data = validated_data.pop('company', {})
        company = instance.company
        for key, val in company_data.items():
            setattr(company, key, val)
        company.save()

        for key, val in validated_data.items():
            setattr(instance, key, val)
        instance.save()

        return instance

    class Meta:
        model = CompanyManager
        fields = ("pk", "user", "company", "display_name")
        read_only_fields = ("display_name",)

email的{​​{1}}字段中添加验证器之前,这一切都正常工作:

UserMeSerializer

现在验证将失败,因为UserMeSerializer没有获得class UserMeSerializer(serializers.ModelSerializer): email = serializers.EmailField( validators=[UniqueValidator( queryset=User.objects.all(), message=_("This email address is already used.") )] ) class Meta: model = User fields = ( 'pk', 'first_name', 'last_name', 'username', 'email', 'date_joined', 'last_login' ) read_only_fields = ('pk', 'date_joined', 'last_login') 参数,因此唯一检查不知道它找到的电子邮件地址是我们正在检查的地址...... see the source of UniqueValidator

所以我的问题是:如何告诉instance我正在UserMeSerializer实例上工作?我应该覆盖companymanager.user吗?

1 个答案:

答案 0 :(得分:-1)

我相信编写一个扩展UniqueValidator的自定义验证器会有所帮助。 您可以检查上下文并相应地设置self.instance。为此,您必须实施set_context()方法。