Home > Back-end >  AttributeError when attempting to get a value for field
AttributeError when attempting to get a value for field

Time:09-16

I have a very weird issue in my Django project.

Here is my model:

class Connection(models.Model):
    user = models.ForeignKey(User, related_name='exchange_connections', on_delete=models.CASCADE)
    exchange = models.ForeignKey(Exchange, related_name='connection_exchange', on_delete=models.CASCADE)

    date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
    last_updated = models.DateTimeField(auto_now=True, blank=True)

Here is my serialiser:

class ConnectionSer(serializers.ModelSerializer):

    class Meta:
        model = Connection
        fields = '__all__'

And my view:

class UserPortfolioViewSet(views.ModelViewSet):
    serializer_class = ConnectionSer
    queryset = Connection.objects.all()
    permission_classes = (permissions.IsAuthenticated, core_permissions.IsMineOnly)

    def list(self, request):
        try:
            user = request.user
        except:
            return HttpResponseBadRequest('No user')

        connections = user.exchange_connections.all()

        return Response(self.serializer_class(connections).data, status=status.HTTP_200_OK)

I get this error from the view (GET):

Got AttributeError when attempting to get a value for field user on serializer ConnectionSer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'user'.

Which makes no sense to me because I don't create any exchange property in my serializer class..? And I also don't understand the last line: 'QuerySet' object has no attribute 'user'.

CodePudding user response:

It looks like you want to filter your queryset based on the active user. You can override the get_queryset method to do this. Furthermore, you already have the IsAuthenticated permission class on your ViewSet, so you don't need to check for active user:

class UserPortfolioViewSet(views.ModelViewSet):
    ...

    def get_queryset(self):

        # get the queryset:
        queryset = self.queryset

        # get the active user:
        user = self.request.user

        # filter queryset based on user:
        queryset = quseryset.filter(user=user)

        # return the fitlered queryset:
        return queryset

CodePudding user response:

This error is caused by passing a collection/list of Connection instances to the serializer, but not flagging the serializer to use many=True, so just add that to prevent the error:

        return Response(self.serializer_class(connections, many=True).data, status=status.HTTP_200_OK)
                                                          # ^^^ Add this

But other than that, @Daniel's answer would be a better way to go to let the ModelViewSet handle all the serialization for you.

  • Related