Django Rest框架嵌套序列化程序不返回validated_data中的关系值

时间:2017-09-01 03:51:27

标签: python django serialization django-rest-framework

我已正确定义了一切。 (GET正常工作)我可以通过嵌套序列化程序获取用户详细信息。但是当我 PUT 时,我没有在UserSerializer中的update方法中获得validated_data。

models.py

class UserProfile(models.Model):

    user = models.ForeignKey(User, related_name='users', 
    on_delete=models.CASCADE)    
    phone_number = models.CharField(max_length=15)
    known_languages = models.CharField(max_length=100)
    date_updated = models.DateTimeField(auto_now=True)     
    user_domain = models.CharField(max_length=100, default=None)

serializers.py

class UserProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserProfile
        fields = ['phone_number', 'known_languages', 'user_domain']

class UserSerializer(serializers.ModelSerializer):

    users = UserProfileSerializer()

    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'username', 'email', 'users']

    def update(self, instance, validated_data):
        import pdb;pdb.set_trace()
        #here I am not getting users value. it is returning empty list
        return instance

views.py

def put(self, request, pk):

        user_obj = self.get_object(pk)
        request.POST._mutable = True
        request.data['users'] = { 'phone_number': request.data.pop('phone_number'), 'user_domain': request.data.pop('user_domain'), 'known_languages': request.data.pop('known_languages') }
        request.POST._mutable = False
        serializer = UserSerializer(user_obj, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

任何人都可以提供帮助......

2 个答案:

答案 0 :(得分:0)

data = request.data.dict()
data['users'] = { 'phone_number': request.data.pop('phone_number'), 'user_domain': request.data.pop('user_domain'), 'known_languages': request.data.pop('known_languages') }
serializer = UserSerializer(user_obj, data=data, partial=True )

对我来说非常适合

答案 1 :(得分:0)

删除这三行:

request.POST._mutable = True
request.data['users'] = { 'phone_number': request.data.pop('phone_number'), 'user_domain': request.data.pop('user_domain'), 'known_languages': request.data.pop('known_languages') }
request.POST._mutable = False

只需在update内使用:

def update(self, instance, validated_data):
    request = self.context.get('request')
    data = request.data.copy()
    users = {
        'phone_number': data.get('phone_number'),
        'user_domain': data.get('user_domain'),
        'known_languages': data.get('known_languages')
    }
    # your code ...