gpt4 book ai didi

python - 具有多个模型(表)的 Django 分页

转载 作者:行者123 更新时间:2023-12-01 03:11:50 26 4
gpt4 key购买 nike

我们有多个模型(表)用于存储客户的订单类别。

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 分页吗?

最佳答案

您可以执行以下操作来链接您的查询集:

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)
...

关于python - 具有多个模型(表)的 Django 分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42832219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com