-1

I am using viewset in rest framework. I am getting same objects in different paginated pages. How can I avoid it.

class Viewset(viewsets.ModelViewSet):
    queryset = Model.objects.all().order_by('?')
    serializer_class = MySerializer
    pagination_class = StandardPagination
  • You need to write logic that for e.g. caches what instances user saw on certain page and exclude them on next pages. You can use session or cookies for that, it's not trivial like customizing view settings but for sure it's possible. – Patryk Szczepański Aug 10 '22 at 09:11
  • If you use random order_by everytime you run querry its randomize again so it is possible to get the same records. Maby you should somehow remeber this random order_by per user. – Waldemar Podsiadło Aug 10 '22 at 09:45

1 Answers1

0

I think you can upload already fetched ids when calling the GET API.

import json
class Viewset(viewsets.ModelViewSet):
    queryset = Model.objects.all()
    serializer_class = MySerializer
    pagination_class = StandardPagination

    def get_queryset(self):
        qs = super().get_queryset()
        exclude_ids = self.request.GET.get('exclude_ids')
        if exclude_ids :
            ids = json.loads(exclude_ids)
            return qs.exclude(id__in = ids)
        return qs
            

Of course, in the frontend, you need to upload the fetched ids array. For example,

localhost:8080/...?exclude_ids=[1,3,10,5]
Metalgear
  • 3,391
  • 1
  • 7
  • 16