使用基于类的基于日期的通用视图替换num_latest?

时间:2011-09-12 00:05:16

标签: django django-generic-views django-class-based-views

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

在1.2中我们有num_latest,我们可以放入我们的信息dict来获取最新的项目。对于新的基于类的通用视图,这似乎不存在。

我可以将paginate_by设置为5并且不使用模板中的分页链接,但是人们仍然可以通过手动敲击网址(我不想要)来查看旧条目。此外,我不希望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]

我得到的评论几乎与评论中提到的相同: 切片拍摄后无法对查询重新排序。

2 个答案:

答案 0 :(得分: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_listitems查询集在后者被切片后不一致。我认为要解决这个问题,你需要重新生成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)
但如果它没有这个,我就不会碰它,因为它看起来太乱了。

答案 1 :(得分: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'
),
相关问题