且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将多个Django模型一起收集到单个列表中?

更新时间:2023-09-16 11:12:10

解决方案是将抽象类转换为一个真正的,然后我可以收集。


I have a fairly straightforward blog in Django, with separate models for Article and Link. I want to have a loop in my template that lists them both in date order, which means something like this:

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

I'm not sure how to do this. Do I have to grab Articles.objects.order_by('post_date') and Links.objects.order_by('post_date') separately, merge them, and reorder? Or is there a nicer Django-ish/Pythonic way to accomplish this?

If it helps, Posts and Links are both subclasses of an abstract class, Post, but as it's an abstract class it appears I can't run collections on it.

Turns out the solution is to turn the abstract class into a real one, and then I can collect over that.