Reputation: 3374
I have a view that paginates records (10 per page) as follows:
class Foo(models.Model):
bar = models.BooleanField(db_index=True)
user = models.ForeignKey(User, db_index=True, editable=False)
baz = models.CharField(max_length=120)
created = models.DateTimeField(db_index=True, auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = ('id', 'username')
class FooSerializer(ModelSerializer):
user = UserSerializer()
class Meta:
model = Foo
class FooPagination(PageNumberPagination):
page_size = 10
class FooView(ListAPIView):
serializer_class = FooSerializer
pagination_class = FooPagination
def get_queryset(self):
user = self.request.user
'''
Do something here (or when page is requested) with each record on
the current page.
'''
return Foo.objects.filter(bar=true, user=user).order_by('created')
How can I process the Foo records that are only on the current page?
Upvotes: 0
Views: 187
Reputation: 111255
Maybe there is a better solution, but I had to roll out my own View class to do post processing after the queryset is filtered and paginated but before it is serialized:
class DecoratedListModelMixin(object):
"""
Apply a decorator to the list view before serializing
"""
def list(self, request, *args, **kwargs):
has_decorator = (hasattr(self, 'decorator') and self.decorator is not None)
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
if has_decorator:
serializer = self.get_serializer(self.decorator(page, request), many=True)
else:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
if has_decorator:
serializer = self.get_serializer(self.decorator(queryset, request), many=True)
else:
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
class DecoratedListAPIView(DecoratedListModelMixin, generics.GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
Usage:
class FooView(DecoratedListAPIView):
serializer_class = FooSerializer
pagination_class = FooPagination
decorator = foo_decorator
def get_queryset(self):
user = self.request.user
return Foo.objects.filter(bar=true, user=user).order_by('created')
# queryset contains current page only
def foo_decorator(view, queryset, request):
for foo in queryset:
#...
return queryset
Upvotes: 1