Python elasticsearch-dsl django pagination

后端 未结 4 470
长发绾君心
长发绾君心 2021-01-02 04:35

How can i use django pagination on elasticsearch dsl. My code:

query = MultiMatch(query=q, fields=[\'title\', \'body\'], fuzziness=\'AUTO\')

s = Search(usin         


        
4条回答
  •  盖世英雄少女心
    2021-01-02 05:17

    A very simple solution is to use MultipleObjectMixin and extract your Elastic results in get_queryset() by overriding it. In this case Django will take care of the pagination itself if you add the paginate_by attribute.

    It should look like that:

    class MyView(MultipleObjectMixin, ListView):
        paginate_by = 10
    
        def get_queryset(self):
            object_list = []
            """ Query Elastic here and return the response data in `object_list`.
                If you wish to add filters when querying Elastic,
                you can use self.request.GET params here. """
            return object_list
    

    Note: The code above is broad and different from my own case so I can not guarantee it works. I used similar solution by inheriting other Mixins, overriding get_queryset() and taking advantage of Django's built in pagination - it worked great for me. As it was an easy fix I decided to post it here with a similar example.

提交回复
热议问题