1

我在 Django 中有一个相当简单的博客,文章和链接有单独的模型。我想在我的模板中有一个循环,按日期顺序列出它们,这意味着这样的事情:

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 的子类,但由于它是一个抽象类,因此我无法在其上运行集合。

4

3 回答 3

1

原来解决方案是将抽象类变成一个真正的类,然后我可以收集它。

于 2012-06-01T11:38:24.157 回答
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)
于 2012-06-02T12:43:54.047 回答
0

好吧,显而易见的答案是让 Post 成为一个具体的类。否则,您可能不得不压缩 ORM 并诉诸手工编码的 SQL 或手动合并/排序您的两个查询集。鉴于数据集的规模较小,我会选择最后一个解决方案。

于 2012-06-01T11:45:19.830 回答