如何实现嵌套对象的序列化

时间:2015-09-08 08:18:08

标签: django serialization django-rest-framework

在django中使用function based views实现了基本身份验证系统。

尝试将其升级为class based views

通过继承django UserProfile模型来创建User

需要序列化UserProfile并返回客户端

User型号:

from django.contrib.auth.models import User

UserProfile型号:

class UserProfile(models.Model):
id = models.AutoField(primary_key=True)
user = models.OneToOneField(User)
profile_picture = models.ImageField(upload_to='documents', blank=True)

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

UserSerializer

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('username','password', 'first_name', 'last_name', 'email',)
        write_only_fields = ('password',)
        read_only_fields = ('is_staff', 'is_superuser', 'is_active', 'date_joined',)

        def restore_object(self, attrs, instance=None):
            user = super(UserSerializer, self).restore_object(attrs, instance)
            user.set_password(attrs['password'])
            return user

UserProfileSerializer

class UserProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    class Meta:
        model = UserProfile
        fields = ('id','user','profile_picture',)

views.py

class AuthView(APIView):
    authentication_classes = (BasicAuthentication,)
    def post(self, request, *args, **kwargs):
        login(request, request.user)
        content={ 'user':UserProfileSerializer(request.user).data,'token':csrf.get_token(request)}
        return Response(content)  
views.py中的

UserProfileSerializer(request.user).data无效。 但相反,如果我使用:  UserSerializer(request.user).data,它给了我结果(按预期):

{'first_name': '', 'username': 'admin', 'email': 'a@a.com', 'last_name': '', 'password': 'pbkdf2_'}

但我还希望用户的其他属性也像profile_picture一样序列化,因此类似

UserProfileSerializer(request.user).data

对我有用。

问题

  1. 是否可以序列化包含FileField

  2. 的模型
  3. 如何序列化嵌套对象并返回其数据?

  4. 有点初学者。

1 个答案:

答案 0 :(得分:1)

是的,可以序列化FileField。问题是您的配置文件序列化程序需要UserProfile模型而不是User模型。试试这个:

content={ 'user':UserProfileSerializer(request.user.user_profile).data,'token':csrf.get_token(request)}