Django REST and ModelViewSet filtering

Question:

I was previously using APIViews such as the following:

views.py

class AllProgramsApi(APIView):

    def get(self, request):
        user = self.request.user
        userprograms = Program.objects.filter(user=user)
        serializer = ProgramSerializer(userprograms, many=True)
        return Response(serializer.data)

here’s my model:

class Program(models.Model):

    program_name = models.CharField(max_length=50)
    program_description = models.CharField(max_length=250)
    cycles = models.ManyToManyField(Cycle)
    is_favourite = models.BooleanField(default="False")
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def get_absolute_url(self):
        return reverse('programs:program', kwargs={'pk': self.pk})

    def __str__(self):
        return self.program_name

Now I’ve discovered ModelViewSet, which looks very convenient, but I can’t seem to be able to filter for the user as I was previously doing in the APIView.

my attempt at views.py with ModelViewSet is the following and it works but I get all the content and not just the content related to a single user.

class AllProgramsApi(ModelViewSet):
    serializer_class = ProgramSerializer
    queryset = Program.objects.all()

How can I tweak the ModelViewSet so that it displays only the content related to the user who sends the request? What is the best method?

Thanks.

Asked By: Giulia

||

Answers:

You can use get queryset method,if you know more refer the doc Filtering against the current user

class AllProgramsApi(ModelViewSet):
    serializer_class = ProgramSerializer
    queryset = Program.objects.all()
    def get_queryset(self):
        queryset = self.queryset
        query_set = queryset.filter(user=self.request.user)
        return query_set
Answered By: Robert

there are permission_classes in django you can add permissions as per your requirements or you can create custom permissions

you would get better idea from django permission

or you can create your queryset by defining get_queryset method.

Answered By: bhatt ravii

I have a question and if I wanted to filter it by a field, in this case if I wanted to filter it by program_name?

Answered By: daniel Alvarez