[Django]-Django Pagination with multiple models (tables)

7👍

You can do something like this to chain your querysets:

from itertools import chain

book_orders = BookOrder.objects.all()
shoe_orders = ShoeOrder.objects.all()    
mobile_orders = MobileOrder.objects.all()
orders = list(
            sorted(
                chain(book_orders, shoe_orders, mobile_orders),
                key=lambda objects: objects.created_at
            ))
paginator = Paginator(orders, 5)

But I think the better way is to refactor your models and use Multi-Table-Inheritance. Then you have a base class Order and you can do the pagination on this class:

class Order(models.Model):
    user = models.ForeignKey(User)
    order_details = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class BookOrder(Orders):
    book = models.CharField(max_length=255)
    ...

Leave a comment