0

Using DRF and DRF-nested-routers

Here's my code:

class MemberViewSet(viewsets.ViewSet):
    queryset = GroupMember.objects.all()
    serializer_class = GroupMembersSerializer


    def create(self, request, group_pk=None):
        queryset = self.queryset.all()
        serializer = GroupMembersSerializer(queryset)
        return Response(serializer.data)

But once a new Member is posted the error "QuerySet' object has no attribute 'user' comes up

Any help?

Danny
  • 889
  • 3
  • 10
  • 19

2 Answers2

2

To serialize a queryset (or list of objects) you need to pass many=True

serializer = GroupMembersSerializer(queryset, many=True)

Otherwise it thinks you want to serialize a single GroupMember instance, which is why it tried to access the user attribute on it

bakkal
  • 54,350
  • 12
  • 131
  • 107
1

If isn't too late in your development and you have the choice, you may want to check out https://github.com/chibisov/drf-extensions. It does routers nesting in a non-intrusive manner - you won't be required to overwrite the viewsets basic methods.

I've learned form the past that drf-nested-routers will interfere with the underlying viewset methods which enable pagination and filtering on your class:

  • get_queryset
  • get_serializer_class
  • get_serializer
  • get_object

In my opinion affects too much from the Viewset design and functionality for what it offers.

Roba
  • 646
  • 4
  • 13