簡體   English   中英

如何將多個Django模型收集到一個列表中?

[英]How do I collect multiple Django models together into a single list?

我在Django中有一個相當簡單的博客,其中有用於Article和Link的單獨模型。 我想在我的模板中有一個循環,按日期順序將它們都列出,這意味着像這樣:

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') ,將它們合並並重新排序? 還是有一種更好的Django-ish / Pythonic方法來實現這一目標?

如果有幫助,則Posts和Links都是抽象類Post的子類,但是由於它是一個抽象類,因此看來我無法在其上運行集合。

事實證明,解決方案是將抽象類變成一個真正的類,然后我可以收集它。

好吧,最明顯的答案是讓Post具體課程。 否則,您可能不得不壓縮ORM並采用手工編碼的SQL或手動合並/排序兩個查詢集。 鑒於數據集的大小,我將選擇最后一個解決方案。

重構可能是更好的解決方案,但這是另一個可以完成此工作的解決方案:

創建一個自定義管理器:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM