Suppose that we have page like dashboard,
More than one type object is listed:
campaigns = Campaign.objects.all()
products = Product.objects.filter(campaign__name__isnull=False)
comments = CustomerComment.objects.filter(selected=True)
'products' : products,
return render(request, 'dashboard.html', context)
It will be a single page and the number of objects to be displayed on the page can be determined.
Which one is better solution?
campaigns = Campaign.objects.all()[:6]
products = Product.objects.filter(campaign__name__isnull=False)[:9]
comments = CustomerComment.objects.filter(selected=True)[:5]
campaign_paginator = Paginator(campaigns, 6)
page_number = 1
campaign_page_obj = campaign_paginator.get_page(page_number)
product_paginator = Paginator(products,9)
product_page_obj = product_paginator.get_page(page_number)
comment_paginator = Paginator(comments, 5)
comment_page_obj = comment_paginator.get_page(page_number)
Which approach is better especially in terms of performance and optimization?
From a query perspective, they’re effectively identical. (See the source code for Paginator and Page to see that it’s getting a slice of a result set.)
From a page-construction/UI/UX perspective, are you going to put the “page selection” widgets with each section? (A person can select different pages for each category) Or do you want to just have one set of page selection widgets that apply to all three categories?
If the former, then your view needs to accept three parameters for the different pages being shown for each.
If the latter, then using three paginators is creating some (really) negligible overhead by creating Page objects for two of the three sets.
Firstly, thanks for the reply.
Assume that we don’t really need a pagination.
ie, user only could see the objects reflected on the first page.
In that case, they don’t have a difference in terms of performance and data load, right?
It’s not a difference in “performance and data load”, you’re only talking about the difference in creating 3 instances of 2 different objects.
More importantly, I think it’s an issue of clarity - creating instances of Paginator that aren’t being used might obstruct the real purpose of that block of code.