2012-01-20 31 views
3

我有兩種型號:PostType1PostType1按不同命名的字段排序兩種不同型號

class PostType1(models.Model): 
    ... 
    created_date = models.DateTimeField(_('created date'), blank=True, null=True) 

class PostType2(models.Model): 
    ... 
    publish_date = models.DateTimeField(_('publish date'), blank=True, null=True) 

我做一個查詢既獲得:

posts_type1 = PostType1.objects.all() 
posts_type2 = PostType2.objects.all() 

我知道如何把它們連:

posts = chain(posts_type1,posts_type2) 

我正在尋找一種方式按日期降序對它們進行排序。
這可能嗎?或者我應該看看生sql?

回答

3

因此,如果您的計劃是對兩個查詢集的聯合進行排序,則必須使用sorted方法。我會去這樣的:

sorted(chain(posts_type1, posts_type2), 
     key=lambda x: x.created_date if isinstance(x, PostType1) 
            else x.publish_date) 
+0

我試圖做同樣的事情,但我排序的參數有點笨拙,不會說錯。非常感謝你。 – geros

1

每個查詢可以執行使用order_by排序:

posts_type1 = PostType1.objects.all().order_by('-created_date') 
posts_type2 = PostType2.objects.all().order_by('-publish_date') 

如果你想整個結果進行排序,你可以使用,而不是chain自定義迭代器。只有兩個型號的例子(儘管不一定是最乾淨的一個):

def chain_ordered(qs1, qs2): 
    next1 = qs1.next() 
    next2 = qs2.next() 
    while next1 is not None or next2 is not None: 
     if next1 is None: yield next2 
     elif next2 is None: yeild next1 
     elif next1 < next2: 
      yield next1 
      try: 
       next1 = qs1.next() 
      except StopIteration: 
       next1 = None 
     else: 
      yield next2 
      try: 
       next2 = qs2.next() 
      except StopIteration: 
       next2 = None 

使用sorted將工作過,但據我所知它會在分揀過程中從數據庫中檢索所有項目的StefanoP的建議,該建議可能會或可能不會對你的關心。

+0

事實是,我想循環回所有我的分貝。我更喜歡StefanoP的方法,因爲它是pythonic比方說。 Thnak你的職位。 – geros

+0

@geros當然,我更喜歡他的解決方案。如果你使用遊標來檢索你的行(例如,如果你的整個數據太大而不能適應內存),Mine只會很有用。 – mgibsonbr