Django REST框架:Update给出了嵌套序列化程序的错误

时间:2014-05-29 21:58:39

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

我有两个型号

验证用户模型和UserProfile

UseProfile是:

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    name = models.CharField(_lazy(u'Name'), max_length=255)

我正在使用这些序列化器:

from rest_framework import serializers
from django.contrib.auth.models import User

from oneanddone.users.models import UserProfile

    class UserProfileSerializer(serializers.ModelSerializer):

        class Meta:
            model = UserProfile
            fields = ('name',)


    class UserSerializer(serializers.ModelSerializer):
        profile = serializers.RelatedField()

        class Meta:
            model = User
            fields = ('id', 'username', 'email', 'groups', 'profile')

两个序列化程序的视图是:

class UserListAPI(generics.ListCreateAPIView):
    """
    API endpoint used to get a complete list of users
    and create a new user.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer


class UserDetailAPI(generics.RetrieveUpdateDestroyAPIView):
    """
    API endpoint used to get, update and delete user data.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_field = 'email'

嵌套序列化程序适用于创建/删除查询,但适用于更新查询,如:

pdata = {"username":"testusername", "email":"test@testmail.com","profile":[{"name":"Changed Name"}]}

requests.patch('http://localhost:8000/api/v1/user/test@testmail.com/',data=json.dumps(pdata), headers={'Authorization':'Token bd876bfa04843c6ce1b82c84e27cd510f68dfbbd','Content-Type': 'application/json'}).text

我收到错误消息“UserProfile”对象不可迭代。追溯:http://pastebin.com/RA7JWFua

可以使用嵌套的序列化器来完成这样的更新吗?还请提供我必须添加的自定义代码,以使其正常工作。

1 个答案:

答案 0 :(得分:0)

我通过对序列化程序和视图进行以下更改来实现此目的。

两种型号的序列化器:

from django.contrib.auth.models import User

from rest_framework import serializers

from oneanddone.users.models import UserProfile


class UserProfileSerializer(serializers.ModelSerializer):

    class Meta:
        model = UserProfile
        fields = ('name', 'username', 'privacy_policy_accepted')


class UserSerializer(serializers.ModelSerializer):
    profile = UserProfileSerializer(required=False, many=False)

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'groups', 'profile')

两个序列化程序的视图:

class UserDetailAPI(generics.RetrieveUpdateDestroyAPIView):
    """
    API endpoint used to get, update and delete user data.
    """
    lookup_field = 'email'
    queryset = User.objects.all()
    serializer_class = UserSerializer


class UserListAPI(generics.ListCreateAPIView):
    """
    API endpoint used to get a complete list of users
    and create a new user.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

更新查询可以写在类似的行上,如:

# Change Profile Data(name, username, privacy_policy_accepted)
        changed_data = {'username': 'testname', 'email': 'test@test.com',
                        'profile': {'name': 'Changed Test Name', 'username': 'testname123', 'privacy_policy_accepted': False}}
        response = self.client.patch(user_uri, changed_data, format='json')

免责声明:所有这些代码段现在都是Mozilla组织下的应用程序的一部分,并在Mozilla许可下发布。

可在此处找到原始代码的链接:

SerializersViewsUnit Tests for Profile Update