简体   繁体   English

如何在不使用 REST 框架的情况下在 Django 和 React 应用程序中实现分页?

[英]How to implement pagination in a Django and React app without using the REST framework?

I am working on a website whose back-end is in Django and front-end is developed using React.我在一个网站上工作,它的后端在 Django 中,前端是使用 React 开发的。 I want to add the pagination feature in the website but don't know how it will be implemented in the frontend part.我想在网站中添加分页功能,但不知道在前端部分将如何实现。

I want to send the total page count to the react app.我想将总页数发送到反应应用程序。

I have written the following code in my views function till now到目前为止,我已经在我的视图函数中编写了以下代码

def index(request):
    influencers = Influencer.objects.all()

    paginator = Paginator(influencers,16)
    page = request.GET.get('page')
    paged_listings = paginator.get_page(page)
    user_list = UserList.objects.all().filter(user_id = request.user.id)

    queryset = list(chain(paged_listings,user_list),paginator.count)
    ser_query = serializers.serialize('json', queryset)
    return HttpResponse(ser_query)

Also I am not using REST framework to develop the back-end site.此外,我没有使用 REST 框架来开发后端站点。

I want to know what information I have to send to the React front-end site for this to work.我想知道我必须向 React 前端站点发送哪些信息才能使其正常工作。 How should I proceed?我应该如何进行?

I'd recommend you do use django-rest-framework because it's probably easier with pagination.我建议您使用 django-rest-framework 因为分页可能更容易。

However, if you want to avoid that you could pass your own structure (obviously, you may need to pass other information such as next page/previous page etc).但是,如果您想避免这种情况,您可以传递自己的结构(显然,您可能需要传递其他信息,例如下一页/上一页等)。

The challenge here is ensuring everything is JSON serializable - that means for Queryset you have to use .values() and wrap the result with list().这里的挑战是确保一切都是 JSON 可序列化的——这意味着对于Queryset你必须使用 .values() 并用 list() 包装结果。 For Paginator you need to wrap with list().对于Paginator您需要使用 list() 进行包装。

from django.http.response import JsonResponse

def index(request):
    influencers = Influencer.objects.all().values()

    paginator = Paginator(influencers,16)
    page = request.GET.get('page')
    paged_listings = paginator.get_page(page)
    user_list = UserList.objects.all().filter(user_id = request.user.id).values()

    queryset = list(chain(paged_listings,user_list),paginator.count)
    content = {'total_page_count': paginator.num_pages, 'data': queryset}
    return JsonResponse(content)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM