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 ?
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)
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With