eadwinCode / django-ninja-extra

Django Ninja Extra - Class-Based Utility and more for Django Ninja(Fast Django REST framework)
https://eadwincode.github.io/django-ninja-extra/
MIT License
394 stars 33 forks source link

How to make Paginated response from queryset ? #195

Open Elixir-MeetThoriya opened 3 weeks ago

Elixir-MeetThoriya commented 3 weeks ago
   @http_get(
        path="",
        response={
            HTTPStatus.OK: PaginatedResponseSchema[CountrySchema] | List[CountrySchema],
            HTTPStatus.INTERNAL_SERVER_ERROR: ErrorSchema
        },
        summary="Country List",
        description="This endpoint retrieves a list of countries.",
        url_name="country_list"
    )
    # @paginate()  # use default pagination (which define in setting.py)
    @ordering(Ordering, ordering_fields=['name', 'code'])
    @searching(Searching, search_fields=['name', 'code'])
    def list(self):
        try:
            if self.request.headers.get('no_page') == 1:
                return self.model.objects.all()
            else:
                return .................

Hiiii @eadwinCode this is my list api .. default pagination class = from ninja_extra.pagination import PageNumberPaginationExtra i need to send condition base response (paginated or non-paginated) so in my list api-function how to make a paginated response, without using "@paginate" decorator.

eadwinCode commented 1 week ago

@Elixir-MeetThoriya you can make your API function by return paginated response by returning PaginatedResponseSchema instance

...
items = list(self.mode.objects.all()
return PaginatedResponseSchema[CountrySchema](count=len(items), results=items, next=None, previous=None)
Elixir-MeetThoriya commented 1 week ago

@eadwinCode i know this way but i think is not proper way , because if we use return return PaginatedResponseSchema[CountrySchema](count=len(items), results=items, next=None, previous=None)

pagination not work.

please give me another way which use default paginate/pagination functionality.

    @http_get(
        path="",
        response={
            HTTPStatus.OK: PaginatedResponseSchema[ActivitySchema] | List[ActivitySchema],
            HTTPStatus.INTERNAL_SERVER_ERROR: ErrorSchema
        },
        summary="Activity List",
        description="This endpoint retrieves a list of activity.",
        url_name="activity_list"
    )
    # @paginate()
    @ordering(Ordering, ordering_fields=['name'])
    @searching(Searching, search_fields=['name'])
    def list(self):
        try:
            if self.request.headers.get('no_page') == 1:
                 return self.model.objects.all()
            else:
                 # return super().list(filter_kwargs={'center_id': self.center_id})
                 qs = list(self.model.objects.all())
                 return PaginatedResponseSchema[ActivitySchema](count=len(qs), results=qs, next=None, previous=None)