关于用户模型的OneToOne关系和NestedSerializer问题

时间:2017-07-13 18:04:58

标签: django serialization django-rest-framework

我正在尝试登录应用,包括注册,身份验证等... 我收到此错误:

AttributeError: Got AttributeError when attempting to get a value for field 'user' on serializer 'PictureUserSerializer'. The serializer field might be named incorrectly and not match any attribute or key on the 'User' instance. Original exception text was: 'User' object has no attribute 'user'.

但是,当我查看我的管理页面时。用户已使用正确的信息进行了注册。我不觉得这个错误来自哪儿,我必须做错事。这是我的代码:

logginapp / models.py

from django.db import models
from django.contrib.auth.models import User

class PictureUser(models.Model):
    user = models.OneToOneField(User) #OneToOne link to the Django's User Model               
    avatar = models.ImageField(null=True, blank=True, upload_to="avatars/")

    def username(self, user):
        return user.username

    def password(self, user):
        return user.password

    def email(self, user):
        return user.email

loginapp / serializer.py

from django.core.validators import validate_email
from django import forms
from rest_framework import serializers
from loginapp.models import PictureUser

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username', 'password', 'email')
        write_only_fields = ('password',)


class PictureUserSerializer(serializers.ModelSerializer):
    """                                                                                       
    Serializer to put the PictureUser model into JSON                                         
    """
    user = UserSerializer()

    class Meta:
        model = PictureUser
        fields = ('user', 'avatar')
        read_only_fields = ('created',)

    def create(self, validated_data):
        print (validated_data)
        return User.objects.create_user(validated_data['user']['username'], validated_data['user']['email'],
            validated_data['user']['password']
    )

loginapp / view.py

from django.shortcuts import render
from rest_framework import generics
from .serializer import PictureUserSerializer
from .models import PictureUser

class PictureUserCreateView(generics.ListCreateAPIView):
    """                                                                                       
    This class define the Create behaviour of a PictureUser                                   
    """
    queryset = PictureUser.objects.all()
    serializer_class = PictureUserSerializer

    def perform_create(self, serializer):
        serializer.save()

2 个答案:

答案 0 :(得分:2)

如果您需要从PictureUserSerializer创建用户,那么

def create(self, validated_data):
    user_data = validated_data.pop('user')
    user = User.objects.create_user(**user_data)
    return PictureUser.objects.create(user = user, **validated_data)

答案 1 :(得分:0)

PictureUserSerializer create method需要返回PictureUser个实例,而不是User个实例。