我想创建一个带有嵌套对象数组的ListView。这是我到目前为止所做的尝试:
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 :(得分:1)
错误是因为您的模型不是json可序列化的。
您可以看到@yuwang评论关注嵌套序列化程序http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
或者目前,特别是在这种情况下,您可以将代码更改为:
@property
def students(self):
from pupils.models import Pupils
return list(Pupils.objects.filter(group=self).values())