khsoldier
khsoldier

Reputation: 85

How to paginate 3 different objects in the same page efficiently?

I have 3 different models ModelA,ModelB,ModelC, all related to the user. So, I want to show them in a list ordered by date (infinite scroll down). But it's starting to take too much to load them at once.

My ajax view:

...
list1 = user.modela_list.all()
list2 = user.modelb_list.all()
list3 = user.modelc_list.all()
result = list1 + list2 + list3
return render(request,'template.html',context={'result':result})

The template (I use the regroup templatetag to group them by the DateTimeField they all have):

<div class="tab-pane fade show active" id="tab1" role="tabpanel">

    {% regroup result by date.date as result_list %}
    {% for group_by_date in result_list %}
        <div class="section-title">{{ group_by_date.grouper }}</div>
            <div >
                {% for object in group_by_date.list %}
                    ....
                {% endfor %}
            </div>
        </div>
     {% endfor %}
</div>

This creates something like this:

enter image description here

So now, instead of just loading all the objects I wan't some kind of pagination but I can't figuire it out. How do I get the correct amount of ModelA, ModelB and ModelC objects by date?:

#I can't do just this
list1 = user.modela_list.all()[0:5]
list2 = user.modelb_list.all()[0:5]
list3 = user.modelc_list.all()[0:5]

If I want 15 elements per load, how many of modelA, B and C do I have to show.

I hope I explained myself. Thanks!

Upvotes: 1

Views: 84

Answers (1)

Marta Gonzalez
Marta Gonzalez

Reputation: 26

Just take the 15 first of each model an order by date before passing the result to the template.

list1 = user.modela_list.all().order_by('date')[0:15]
list2 = user.modelb_list.all().order_by('date')[0:15]
list3 = user.modelc_list.all().order_by('date')[0:15]

all_lists = list1 + list2 + list3
result = your_order_by_date_method(all_lists)[0:15]

Upvotes: 1

Related Questions