How to filter an APIView to show user-related messages?

0

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

models.py:

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

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

views.py:

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 when running the code gives me the following error:

  

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

    
asked by anonymous 29.01.2018 / 20:18

1 answer

0

The error you're getting is a Python syntax error, because it's trying to use normaluser in the normaluser statement without having previously created normaluser , basically!

On the filter you want to do, documentation of DRF has examples for this , or by the URL passing a "user id" as its example demonstrates, as well as the% django% object, which contains the authenticated user.

See:

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'd advise you to take a look at here for more details and examples.

Att,

    
30.01.2018 / 15:50