2011-10-02 57 views
4

在我的網站中,我有三個模型,分爲兩個應用程序,所有這些模型都有一個timestamp字段,它定義網站Feed中的外觀順序。我不想爲每個模型創建一個Feed,並按timestamp字段排序查詢單個查詢,而是生成一個包含所有這些對象的提要,並使用相應的模板呈現每個提要,並按timestamp屬性排序。從不同模型生成單一飼料的最佳方式是什麼?

我第一次嘗試將列出所有的對象和他們在一個單獨的列表組合和Python的內部排序他們:

class SiteFeed(Feed): 
    ... 
    def items(self): 
     objects = list(model1.objects.all()) + list(model2.objects.all()) + list(model3.objects.all()) 
     objects.sort(key=lamda obj: obj.timestamp) 
     return = objects 

回答

2

我會從items方法返回一個迭代。在這種情況下,對象的排序和聚合可以用懶惰的方式完成。如果在構造迭代器之前對三個要合併的對象集合進行預先排序,則最終排序只是在每次迭代時從右集合中選擇下一個對象。你明白我的意思嗎?

例如:

 
class SiteFeed(Feed): 
    ... 
    def items(self): 
     i = model1.objects.order_by('timestamp').iterator() 
     j = model2.objects.order_by('timestamp').iterator() 
     k = model3.objects.order_by('timestamp').iterator()
try: u = i.next() except StopIteration: u = None
try: v = j.next() except StopIteration: v = None
try: w = k.next() except StopIteration: w = None ... yield min([u,v,w], key=lambda x: x.timestamp if x else datetime.max) ... # at this point you need to reiterate the iterator # corresponding to the variable that you yielded # and yield again # so, the above code must be in some sort of a loop # until ALL iterators are exhausted

+0

我不習慣迭代器,你可以請提供一個例子代碼ilustrate你的答案?我看不出如何構建該迭代器,但我認爲我理解了一般想法。 –

+0

我已更新我的回答 – akonsu

+0

這是一個簡單的迭代器。問題仍然存在,我需要按照公共屬性'timestamp'排序的所有不同模型的對象。在那個代碼中,只返回'model1'對象。 –

相關問題