2016-04-23 95 views
0

我正在尝试实现基本序列化器,并且我遵循“http://www.django-rest-framework.org/api-guide/serializers/#baseserializer”。需要帮助在Django中实现基本序列化器

我的urls.py:

url(r'^auth/myuser/(?P<pk>[0-9]+)/profile/$', UserProfileViewSet.as_view({'patch':'update'}), name='user-profile'), 

Views.py:

class UserProfileViewSet(viewsets.ModelViewSet): 
    queryset = CustomUser.objects.all() 
    serializer_class = UserProfileSerializer 

    def get(self,request,pk,*args,**kwargs): 
     user_instance = CustomUser.objects.get(pk=pk) 
     dashboard_data = UserProfileSerializer(user_instance) 
     content = {'result': dashboard_data} 
     return Response(content) 

Serializers.py:

class UserProfileSerializer(serializers.BaseSerializer): 
    def to_representation(self,obj): 
      return{ 
      'email':obj.email, 
      'first_name':obj.first_name, 
      'last_name':obj.last_name, 
      'date_of_birth':obj.date_of_birth, 
      'gender':obj.get_gender_display(), 
      'location':obj.location, 
      'calling_code':obj.callingcode, 
      'phone_primary':obj.phone_primary, 
      'phone_secondary':obj.phone_secondary, 
      'website':obj.website 
      } 

但我得到错误“用户对象不是JSON序列化”,并且我没有找到任何不可序列化的用户对象的属性。

我已经在SO上找到了一些答案,但是在django rest框架API指南中找不到类似的步骤。因此寻找与api指南同步的解决方案。

回答

1

串行:

它似乎你需要的是一个ModelSerializer

ModelSerializer类提供了一个快捷方式,可让您自动创建Serializer类,其中fields对应于模型字段。

class UserProfileSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = CustomerUser 
     fields = '__all__' 

我已经设置fields属性__all__表明,模型中的所有字段序列化。但是,你也可以指定哪些字段exaclty包括:

fields = ('email', 'first_name', 'last_name',) # etc. 

视图集:

第二点是关于ModelViewSet,你并不真的需要实现get方法,因为它已经是为您执行。你只需要声明querysetserializer_class就像你已经做了:

class UserProfileViewSet(viewsets.ModelViewSet): 
    queryset = CustomUser.objects.all() 
    serializer_class = UserProfileSerializer 
+0

我同意,我相信这个工程。但我想尝试使用Base序列化器来学习。 –

1

我想你必须在返回之前以JSON格式呈现响应。

class JSONResponse(HttpResponse): 
""" 
An HttpResponse that renders its content into JSON. 
""" 
def __init__(self, data, **kwargs): 
    content = JSONRenderer().render(data) 
    kwargs['content_type'] = 'application/json' 
    super(JSONResponse, self).__init__(content, **kwargs) 

class UserProfileViewSet(viewsets.ModelViewSet): 
    queryset = CustomUser.objects.all() 
    serializer_class = UserProfileSerializer 

    def get(self,request,pk,*args,**kwargs): 
     user_instance = CustomUser.objects.get(pk=pk) 
     dashboard_data = UserProfileSerializer(user_instance) 
     content = {'result': dashboard_data} 
     return JSONResponse(content, status=200) 

你需要以下进口此,

from rest_framework.renderers import JSONRenderer 
from rest_framework.parsers import JSONParser 

如果这不只是工作试图通过dashboard_data到JSONResponse功能