我们有多个模型(表格)用于存储客户类别的订单。
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)
现在我们需要向客户显示基于created_at的订单列表。但它应该是分页的。 任何人都可以建议我如何使用Django分页与多个模型?
答案 0 :(得分:1)
您可以对chain
您的查询集执行以下操作:
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)
但我认为更好的方法是重构模型并使用Multi-Table-Inheritance。然后你有一个基类Order
,你可以在这个类上进行分页:
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)
...