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
字段上,但是如何?
所行有任何日期时间字段?你能粘贴确切的追溯日志吗? – Roshan
除@roshan的评论外,还可以检查如何添加嵌套序列化器:http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects – yuwang
错误发生是因为你的'Pupils'模型不是JSON序列化的。您可以'导入json',然后'返回json.dumps(Pupils.objects.filter(group = self))'以获得解决方法。 – kapilsdv