Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST and ModelViewSet filtering

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.

like image 254
Giulia Avatar asked Nov 30 '22 15:11

Giulia


1 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
like image 183
Robert Avatar answered Dec 04 '22 04:12

Robert