Home > Net >  How to CRUD data that's created only by the current user in DRF?
How to CRUD data that's created only by the current user in DRF?

Time:09-25

Hi Im currently using DjangoRESTFramework to create an API which I would fetch in ReactJS. My app is a project management system where logged in user could create new clients and projects of each client. Now, I would like my DRF to send the data through the API only those which are created by the current/logged in user. What I have so far is as such:

serializers.py:

class Client Serializer(serializers.ModelSerializer):
   class Meta:
      model = Client
      fields = '__all__'

class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
       model = Project
       fields = '__all__'

views.py

class ClientView(viewsets.ModelViewSet):
    serializer_class = ClientSerializer
    queryset = Client.objects.all()
    permission_classes = [IsAuthenticated]
    authentication_classes = (TokenAuthentication, )

class ProjectView(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer
    queryset = Project.objects.all()
    permission_classes = [IsAuthenticated]
    authentication_classes = (TokenAuthentication, )

How can I alter this so that I could only access those data created by the logged in / current user? Thank you so much in advance cheers!

CodePudding user response:

You can override queryset using get_queryset()

Solution:

def get_queryset(self):
  user = self.request.user
  queryset = Project.objects.filter(user=user)
  
  return queryset

Similar to Client View

Hope to help you!

CodePudding user response:

You could use django-filter and then use the username/id/email (or whatever your unique identifiers on your user are) as params like /clients/?user=1.

But as I'm often too lazy to use params in react I create dedicated views which return the data I need for the current user :-)

Eg on your Client ViewSet via a DRF Action:

...
from rest_framework.decorators import action
from rest_framework.response import Response
...

class ClientView(viewsets.ModelViewSet):
    serializer_class = ClientSerializer
    queryset = Client.objects.all()
    permission_classes = [IsAuthenticated]
    authentication_classes = (TokenAuthentication, )

    @action(methods=["get"], detail=False)
    def current_user_clients(self, request, *args, **kwargs):
        user = request.user
        clients = Client.objects.filter(user=user)
        serializer = self.get_serializer(clients, many=True)
        return Response(serializer.data)

Which gives you an url like clients/current_user_clients/

Edit: If you need a pagination in your action you have to explicitly add it like described here How to Paginate within an action in Django Rest Framework

  • Related