Home > Net >  How to limit the number of results in a Django REST serializar?
How to limit the number of results in a Django REST serializar?

Time:12-12

Hi have this serializer:

class ActivitiesSerializer(serializers.ModelSerializer):
    activity = serializers.CharField(source='task.name')
    project = serializers.CharField(source='project.name')
    discipline = serializers.CharField(source='task.discipline.name')

    class Meta:
        model = Activities
        fields = (
            'id',
            'activity',
            'project',
            'discipline',
            )

How can I limit the number of results to 10?

This is my view:

class ActivitiesAPIView(generics.ListCreateAPIView):
    search_fields = ['task__name', 'task__discipline__name', 'project__name']
    filter_backends = (filters.SearchFilter,)
    queryset = Activities.objects.all()
    serializer_class = ActivitiesSerializer

Note that I want to limit the number of results to 10, but I want to search through all the model, so it wouldn't work to just limit my queryset to 10.

CodePudding user response:

You can use pagination:

from rest_framework.pagination import PageNumberPagination

class DefaultPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 1000

Then in View:

class ActivitiesAPIView(generics.ListCreateAPIView):
    pagination_class = DefaultPagination

https://www.django-rest-framework.org/api-guide/pagination/#pagenumberpagination

  • Related