简体   繁体   English

为什么 Django REST Framework 嵌套序列化器 self.instance 总是返回 None?

[英]Why Django REST Framework nested serializer self.instance always returns None?

I have model,我有模型,

class Profile(models.Model)
   user = models.OneToOneField(User)

And my serializer classes are,我的序列化器类是,

class UserSerializer(serializers.ModelSerializer):

   def validate(self, attrs):
       print(self.instance) # Always prints None
       print(self.parent.instance.user) # Prints User instance
       return attrs

   class Meta:
       model = User

class ProfileSerializer(serializer.ModelSerializer):
   user = UserSerializer()

   class Meta:
      Model = Profile

And my view class,而我的视图类,

class ProfileView(APIView):
   def update(self, request):
      profile = ProfileSerializer(request.user.profile, data=request.data, partial=True)
      if profile.is_valid():
          profile.save()
          return Response(status=HTTP_204_NO_CONTENT)
      return Response({'error': profile.errors}, status=status.HTTP_400_BAD_REQUEST)

Why self.instance inside validate() method in nested serializer always returns none?为什么嵌套序列化程序中validate()方法中的self.instance总是不返回任何内容?

When do you see that?你什么时候看到的? On creation?关于创作?

In that case self.instance is populated inside the save() method with the result of create() method that's called after `validate().在这种情况下, self.instance被填充到save()方法中,并在 `validate() 之后调用create()方法的结果。

Here you can read 在这里你可以阅读

When passing an initial object or queryset to a serializer instance, the object will be made available as .instance.将初始对象或查询集传递给序列化程序实例时,该对象将作为 .instance 使用。 If no initial object is passed then the .instance attribute will be None.如果没有传递初始对象,则 .instance 属性将为 None。

When you are in a child serializer, you can access the instance using the parent field, instead the instance field, something like this:当您在子序列化程序中时,您可以使用parent字段而不是instance字段访问instance ,如下所示:

        if self.parent is not None and self.parent.instance is not None:
            instance = getattr(self.parent.instance, self.field_name)
            check_query = check_query.exclude(pk=user.pk)

Seem that you need to do that validation in the parent似乎您需要在父级中进行该验证

https://www.django-rest-framework.org/api-guide/validators/#updating-nested-serializers https://www.django-rest-framework.org/api-guide/validators/#updating-nested-serializers

In the case of update operations on nested serializers there's no way of applying this exclusion, because the instance is not available.在嵌套序列化器上的更新操作的情况下,无法应用此排除,因为实例不可用。

Again, you'll probably want to explicitly remove the validator from the serializer class, and write the code the for the validation constraint explicitly, in a .validate() method, or in the view.同样,您可能希望从序列化程序类中显式删除验证器,并在 .validate() 方法或视图中显式编写验证约束的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM