2017-03-16 115 views
0

我們有多個模型(表格)用於存儲客戶類別明智的訂單。Django與多個模型分頁(表)

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

我的回答有幫助嗎?請接受並點贊。 – ilse2005

回答

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

如果created_at字段是不同的名稱,例如(created,created_at,created_on)會發生什麼? – itsvks