Danny
Danny

Reputation: 929

DRF + Nested-Routers - "QuerySet' object has no attribute 'user'

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?

Upvotes: 0

Views: 475

Answers (2)

Roba
Roba

Reputation: 688

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.

Upvotes: 1

bakkal
bakkal

Reputation: 55448

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

Upvotes: 2

Related Questions