Reputation: 4346
I want to create a ListView with a array of nested objects. Here what I've tried so far:
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)
But it returns a type error:
<Pupils: John Doe> is not JSON serializable
I guess I need to use another serializer on my students
field, but how?
Upvotes: 0
Views: 156
Reputation: 1459
Error is because your model is not json serializable.
you can see @yuwang comment to follow nested serializer http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects
or for now, particular for this case you can change your code to:
@property
def students(self):
from pupils.models import Pupils
return list(Pupils.objects.filter(group=self).values())
Upvotes: 1