2012-01-20 3 views
3

두 모델이 있습니다 : PostType1, PostType1.두 개의 다른 모델을 다른 이름의 필드로 정렬하십시오.

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 보이는거야? 당신이 전체 결과를 정렬하려면

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

, 당신은 대신 chain의 사용자 정의 반복자를 사용할 수 있습니다

답변

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를 사용하여 정렬을 수행 할 수 있습니다. 두 모델의 예 (반드시 불구하고 깨끗한 일) :

가 에게 이
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 
에게 이

도 작동하지만 AFAIK는 정렬하는 동안 데이터베이스에서 모든 항목을 검색합니다 sorted를 사용 StefanoP의 제안, 또는하지 않을 수 있습니다 너에 대한 걱정.

+0

진실은 제가 모든 데이터베이스를 되돌리고 싶습니다. 나는 StefanoP의 방법을 선호 할 것이다. 당신의 게시물에 대해 당신을 Thnak. – geros

+0

@geros 확실히, 나는 그의 해결책도 선호한다. Mine은 커서를 사용하여 행을 검색하는 경우에만 유용합니다 (예 : 전체 데이터가 너무 커서 메모리에 저장할 수없는 경우). – mgibsonbr

관련 문제