Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading