Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Pagination with multiple models (tables)

We have multiple models (tables) for storing orders category wise of a customer .

class BookOrder(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 ShoeOrder(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 MobileOrder(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)

Now we need to show list of orders based on created_at to our customers. But it should be paginated. Can anybody suggest me how to use Django pagination with multiple models ?

like image 955
itsvks Avatar asked Sep 13 '25 07:09

itsvks


1 Answers

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)
    ...
like image 158
ilse2005 Avatar answered Sep 14 '25 21:09

ilse2005