MattBroach / DjangoRestMultipleModels

View (and mixin) for serializing multiple models or querysets in Django Rest Framework
MIT License
549 stars 67 forks source link

Pagination with flat=True option? #5

Closed arayate closed 8 years ago

arayate commented 8 years ago

Is it possible to have DRF style pagination with flat=True option?

Sample response:

{
    "count": 20,
    "next": next_link,
    "previous": prev_link,
    "results": [
       ...
    ]
}
MattBroach commented 8 years ago

Hmm, that should totally be possible. Unfortunately, I'm a little swamped right now so it will probably take me a week or so to look into it, but I would be surprised if we couldn't add hooks to the DRF pagination system. I will investigate.

MattBroach commented 8 years ago

So, I just released a new version that adds support for DRF's built-in pagination classes. The new version is up on PyPi, so you should be able to update the package to get pagination working. The info below is from the new README, but I'm putting it here for your reference:

If (and only if) flat = True on your view, drf-multiple-model supports some of Django Rest Framework's built-in pagination classes, including PageNumberPagination and LimitOffsetPagination. Implementatation might look like this:

from rest_framework import pagination

class BasicPagination(pagination.PageNumberPagination):
    page_size = 5
    page_size_query_param = 'page_size'
    max_page_size = 10 

class PageNumberPaginationView(MultipleModelAPIView):
    queryList = ((Play.objects.all(),PlaySerializer),
                 (Poem.objects.filter(style="Sonnet"),PoemSerializer))
    flat = True
    pagination_class = BasicPagination

which would return:

{
    'count': 6,
    'next': 'http://yourserver/yourUrl/?page=2',
    'previous': None,
    'results': 
        [
            {'genre': 'Comedy', 'title': "A Midsummer Night's Dream", 'pages': 350},
            {'genre': 'Tragedy', 'title': "Romeo and Juliet", 'pages': 300},
            {'genre': 'Comedy', 'title': "The Tempest", 'pages': 250},
            {'title': 'Shall I compare thee to a summer's day?', 'stanzas': 1},
            {'title': 'As a decrepit father takes delight', 'stanzas': 1}
        ]
}

I forgot to mention in the README, I also added a paginate_queryList function. Right now this just calls the built in paginate_queryset, but it's there to override if you want to create some custom pagination. Both PageNumberPagination and LimitOffsetPagination have been tested, but let me know if you have any questions/problems!