简体   繁体   中英

get_queryset does not affect querying in django rest framework ModelViewSet

My ViewSet looks like this:

class ClientViewSet(viewsets.ModelViewSet):
    queryset = models.Client.objects.all()
    serializer_class = serializers.ClientSerializer

    def filter_queryset(self, queryset):
        return models.Client.objects.filter(**self.request.data)

    def get_queryset(self):
        return models.Client.objects.filter(owner=self.request.user)

The model looks like this:

class Client(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    name = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return str(self.id)

So, I'm trying to filter clients so that only the current user's clients are presented to them. However, GET api/clients still returns all the clients of all users. What have I done wrong?

That is because you do not further process the queryset in the filter_queryset . The filter_queryset is one of the next steps in the chain. You should thus further filter the queryset with:

class ClientViewSet(viewsets.ModelViewSet):
    queryset = models.Client.objects.all()
    serializer_class = serializers.ClientSerializer

    def filter_queryset(self, queryset):
        return .filter(**self.request.data)

    def get_queryset(self):
        return models.Client.objects.filter(owner=self.request.user)

You however might want to take a look at the filter_backends [drf-doc] . This allows one to implement filters in a more elegant way. By using **self.request.data , you include potentially a security vulnerability, since the users can query not only on the model, but also on related model objects, and thus for example use binary search to determine fields that are sensitive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM