0

我已经切换到 Django 1.3,以便为基于日期的通用视图进行分页。这很好用,但是有一个页面我想要特定数量的项目但不希望它分页。例如,返回前 5 个新闻条目。

在 1.2 中,我们有 num_latest,我们可以将其放入 info dict 中以获取最新项目。新的基于类的通用视图似乎不存在这种情况。

我可以将 paginate_by 设置为 5,只是不使用模板中的分页链接,但是人们仍然可以通过手动输入 url 来查看旧条目(我不想要)。此外,我不希望 Django 设置我不会使用的分页。

编辑:这是我目前使用的 urlconf 行:

url(r'^$', 
    ArchiveIndexView.as_view(
        model = Entry,
        context_object_name = 'entry_list',
        template_name = 'news/news.html',
        date_field = 'published',
    ), name = 'archive_index'
),

进一步编辑:尝试覆盖 get_dated_queryset 我已将这段代码与上面的 urlconf 结合使用,但新视图称为:

class MainIndex(ArchiveIndexView):
    def get_dated_queryset(self):
        return Entry.objects.all()[:2]

我得到了与评论中提到的几乎相同的错误:一旦切片被获取,就无法重新排序查询。

4

2 回答 2

3

尝试覆盖它:

def get_dated_items(self):
    date_list, items, extra_context = super(MainIndex, self).get_dated_items()
    return (date_list, items[:2], extra_context)
注意:此实现可能会在后者被切片后留下date_list与查询集不一致的地方。items我认为要解决这个问题,您也需要重新生成date_list。有关详细信息,请参阅 SVN 中 BaseArchiveIndexView.get_dated_items 的实现:http: //code.djangoproject.com/browser/django/trunk/django/views/generic/dates.py。像这样的东西可能会起作用:
def get_dated_items(self):
    date_list, items, extra_context = super(MainIndex, self).get_dated_items()
    items = items[:2]
    date_list = self.get_date_list(items, 'year')
    if not date_list:
        items = items.none()
    return (date_list, items, extra_context)
但如果没有它也能起作用,我不会碰它,因为它看起来太乱了。

于 2011-09-12T02:11:56.110 回答
0

我自己遇到了这个确切的问题。我发现使用 ListView(而不是 ArchiveIndexView)可以节省我的时间和麻烦。

对于您的第一段代码,区别在于:

from django.views.generic import ListView


url(r'^$', 
    ListView.as_view(
        model = Entry,
        context_object_name = 'entry_list',
        template_name = 'news/news.html',
        queryset=Entry.objects.all().order_by("-published")[:2],
    ), name = 'archive_index'
),
于 2013-07-26T21:20:48.247 回答