2011-12-21 53 views
1

如何在Django中將別名名稱分配給QuerySet的主表?在QuerySet中分配表別名名稱

queryset = Price.objects 
    queryset = queryset.extra(
    where = ['p1.created = (select max(p2.created) from products_price p2 where p2.product_id = p1.product_id)'] 
) 

我想將'p1'別名設置爲Price主表以在子查詢中使用它。

編輯:請注意,每個產品都有最新的價格。

回答

1

你可以看到SQL查詢做下:

queryset = Price.objects.all() 
print queryset.query 

如果你知道第一個SQL查詢。您可以更好地執行子查詢。

雖然,我做了下:

price_max = Price.objects.all().order_by('-created')[0] 
queryset = Price.objects.filter(created=price_max) 

還是最好的: https://docs.djangoproject.com/en/1.3/topics/db/aggregation/#generating-aggregates-over-a-queryset

from django.db.models import Max 
price_max = Price.objects.aggregate((Max('created'))['created__max'] 
queryset = Price.objects.filter(created=price_max) 
+0

我想獲得最新的價格(這是創建的最大)每個產品。這就是爲什麼我使用帶有過濾器的子查詢「where p2.product_id = p1.product_id」。是否有可能重新彙總它? – jordiburgos 2011-12-23 11:17:15

+0

我想是這樣......試試看吧! – Goin 2011-12-23 11:25:27