How to filter an Apiview to show messages related to a user?

Asked

Viewed 196 times

0

I want to create a view using Apiview, which shows all messages sent by a user specified in the url.

py.models:

class Message(models.Model):
body = models.CharField(max_length=500)
normaluser = models.ForeignKey(User, on_delete=models.CASCADE)

As a User I am using the User table provided by Django.

py views.:

class MessageUserView(APIView):
def get(self, request, pk): # devolve objecto
    normaluser = MessageSerializer(instance=Message.objects.get(normaluser),
    many=False)
    serializer = MessageSerializer(instance=Message.objects.filter(pk=normaluser), 
    many=True)
    return Response(serializer.data)

At this point in executing the code gives me the following error:

Unboundlocalerror at /website/message-user/2 local variable 'normaluser' referenced before assignment

1 answer

0

The error you are receiving is a Python syntax error as you are trying to use normaluser in the statement of normaluser without having previously created normaluser, basically!

On the filter you want to make, own documentation of DRF have examples for this, either by URL passing a "user id" as shown by your example, as for the object request Django, which contains the authenticated user.

Behold:

from myapp.models import Purchase
from myapp.serializers import PurchaseSerializer
from rest_framework import generics

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        This view should return a list of all the purchases
        for the currently authenticated user.
        """
        user = self.request.user
        return Purchase.objects.filter(purchaser=user)

I advise to take a look here for details and examples.

Att,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.