【问题标题】:Replacement for num_latest with class-based date-based generic views?用基于类的基于日期的通用视图替换 num_latest?
【发布时间】:2011-11-14 23:31:40
【问题描述】:

我已切换到 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]

我得到了与 cmets 中提到的几乎相同的错误: 获取切片后无法重新排序查询。

【问题讨论】:

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


    【解决方案1】:

    我自己也遇到了这个问题。我发现使用 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'
    ),
    

    【讨论】:

      【解决方案2】:

      尝试改写它:

      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)
      
      但如果没有这个也可以,我不会碰它,因为它看起来太乱了。

      【讨论】:

      • 遗憾的是没有。我已经尝试过像这样简单地对查询集进行切片:queryset = Entry.objects.all()[:5],但是这给了我以下错误:“一旦切片被获取,就无法过滤查询。”,大概是因为那里切片之后还有一些事情要做。
      • 你在使用 BaseDayArchiveView mixin 的衍生产品吗?
      • 不适用于该网址。我已经编辑了我的原始帖子以显示我当前用于相关视图的 urlconf。
      • 嗯。看起来它会起作用,但它看起来非常混乱,从它的外观来看,我最好要么制作自定义视图或使用 paginate_by 而只是不使用分页。可能代码也更少。如果没有人想出更好的主意,我会将其标记为已回答。谢谢。
      • 任何对你有用的东西。我认为子类化是 django 的目标设计方法。换句话说,如果你想扩展一个视图的功能,你可以继承它,从而创建一个自定义视图。例如,请参见此处:https://docs.djangoproject.com/en/dev/topics/class-based-views/#extending-generic-views
      猜你喜欢
      • 2013-04-02
      • 2012-06-09
      • 2011-08-06
      • 2012-01-28
      • 2011-04-24
      • 2010-10-14
      • 2016-08-06
      • 1970-01-01
      • 2011-07-29
      相关资源
      最近更新 更多