2016-07-27 44 views
0

我想用一個嵌套對象數組創建一個ListView。這裏是我到目前爲止已經試過:REST框架:如何序列化對象?

rest.py

class GroupDetailSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Group 
     fields = (
      'id', 
      'num', 
      'students', 
     ) 

@permission_classes((permissions.IsAdminUser,)) 
class GroupDetailView(mixins.ListModelMixin, viewsets.GenericViewSet): 
    serializer_class = GroupDetailSerializer 

    def get_queryset(self): 
     return Group.objects.all() 

models.py

class Group(models.Model): 
    office = models.ForeignKey(Offices) 
    num = models.IntegerField() 

    @property 
    def students(self): 
     from pupils.models import Pupils 
     return Pupils.objects.filter(group=self) 

但它返回一個錯誤類型:

<Pupils: John Doe> is not JSON serializable

我想我需要使用另一個序列化程序在我的students字段上,但是如何?

+0

所行有任何日期時間字段?你能粘貼確切的追溯日誌嗎? – Roshan

+0

除@roshan的評論外,還可以檢查如何添加嵌套序列化器:http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects – yuwang

+0

錯誤發生是因爲你的'Pupils'模型不是JSON序列化的。您可以'導入json',然後'返回json.dumps(Pupils.objects.filter(group = self))'以獲得解決方法。 – kapilsdv

回答

相關問題