2012-06-01 4 views
1

기사와 링크를위한 별도의 모델로 장고에서 매우 간단한 블로그를 가지고 있습니다. 내 템플릿에 다음과 같이 날짜순으로 나열하는 루프를 만들고 싶습니다.어떻게 여러 장고 모델을 하나의리스트로 모을 수 있습니까?

def listview(request): 
    return render_to_response('index.dtmpl', { 
     'articles' : ArticlesAndLinks.objects.order_by('post_date')[:10] 
    }, context_instance = RequestContext(request) 

잘 모르겠습니다. Articles.objects.order_by('post_date')Links.objects.order_by('post_date')을 따로 따로 가져 와서 병합하고 재정렬해야합니까? 또는이 작업을 수행하기에 더 좋은 장고/파이썬 방법이 있습니까?

만약 도움이된다면, 포스트와 링크는 모두 추상 클래스 인 포스트의 하위 클래스이지만 추상 클래스이므로 콜렉션을 실행할 수는 없습니다.

답변

1

해결책을 끄면 추상 클래스를 실제 클래스로 변환 한 다음이를 수집 할 수 있습니다.

0

글쎄, 확실한 대답은 포스트를 구체적인 클래스로 만드는 것이었을 것입니다. 그렇지 않으면 아마도 ORM을 짜내고 handcoded SQL을 사용하거나 두 개의 쿼리 세트를 수동으로 병합/정렬해야 할 것입니다. 데이터 세트의 크기가 작 으면이 마지막 솔루션으로 이동하십시오.

0

리팩토링은 더 나은 해결책이 될 수 있지만, 여기에 작업 할 수있는 또 다른 하나입니다

사용자 지정 관리자 만들기 :

class PostManager(models.Manager): 
    def mixed(self, first): 
     all_dates = [] 
     articles_dates = Articles.objects.extra(select={'type':'"article"'}).values('id', 'post_date', 'type').order_by('-post_date')[:first] 
     links_dates = Links.objects.extra(select={'type':'"link"'}).values('id', 'post_date', 'type').order_by('-post_date')[:first] 
     all_dates.extend(articles_dates) 
     all_dates.extend(links_dates) 
     # Sort the mixed list by post_date, reversed 
     all_dates.sort(key=lambda item: item['post_date'], reverse=True) 
     # Cut first 'first' items in mixed list 
     all_dates = all_dates[:first] 
     mixed_objects = [] 
     mixed_objects.extend(Articles.objects.filter(id__in=[item['id'] for item in all_dates if item['type'] = 'article'])) 
     mixed_objects.extend(Links.objects.filter(id__in=[item['id'] for item in all_dates if item['type'] = 'link'])) 
     # Sort again the result list 
     mixed_objects.sort(key=lambda post: post.post_date, reverse=True) 
     return mixed_objects 

을 그리고 당신의 추상 모델에서 사용 :

class Post(models.Model): 

    class Meta: 
     abstract = True 

    objects = PostManager() 

다음은 혼합 객체 호출입니다.

Article.objects.mixed(10) 
관련 문제