Django REST and ModelViewSet filtering

2019-07-19 02:27发布

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.

2条回答
孤傲高冷的网名
2楼-- · 2019-07-19 02:52

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.

查看更多
太酷不给撩
3楼-- · 2019-07-19 03:04

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
查看更多
登录 后发表回答