Home > Blockchain >  How to paginate different objects of the same endpoint in Django Rest Framework?
How to paginate different objects of the same endpoint in Django Rest Framework?

Time:01-27

Lest supose that I have a model named Collection. I can create a collection, this collection have two important fields: share_with_company, share_list.

class Collection(models.Model):
    name = models.CharField(max_length=200, blank=False, null=False)
    share_with_company = models.BooleanField(default=False)
    share_list = ArrayField(models.CharField(max_length=15), null=True, blank=True)
    owner = models.CharField(max_length=200, blank=False, null=False)

currently I have an endpoint: /collections and this endpoint need to return something like it:

    {
       shared_with_company:{collections: ..., count: 5}
       shared_list:{collections: ..., count: 12}
       my_collections:{collections: ..., count: 20} //dont shared with anyone, created by the current user
    }

but, in the frontend the user want to paginate just my_collections or just shared_list or shared_with_company. I like performance, so should I create a specifics endpoints to each type of collections? But, everytime the user load the collections page will show 12 (max per page) collections of each (my_collections, shared etc.), and then he will be able to paginate it. I don't know if this is the best way to do it, I think a lot of users send 3 requests everytime the page is loaded.

Another approach: use an endpoint to load the initial page, and this enpoint will make one request to the first page and the paginations will be made with differents endpoints.

I really don't know if there is a better approach or something like that.

CodePudding user response:

The usual approach will be creating three different endpoints. It's okay when user sends 3 requests to the api, actually it may be even better as your frontend can show data more dynamically. Also, you don't need to return all the data every time, just a list user requested.

If you use ModelViewSet, since it's one model for three endpoints, you can just add new actions with @action decorator and override get_queryset. So you will have endpoints like these - collections/shared_with_company, collections/shared_list and collections/my_collections

And in your get_queryset you can determine what queryset you would like to return, for example:

def get_queryset(self):
    queryset = super().get_queryset()
    if self.action == 'list':
        return queryset
    elif self.action == 'shared_with_company':
        return queryset.filter(share_with_company=True)
  •  Tags:  
  • Related