来自Django DetailView的分页 [英] Pagination from a Django DetailView

查看:145
本文介绍了来自Django DetailView的分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个models.py:

  class Partner(models.Model):
...(fields

class Lecture(models.Model):
...(其他与此示例无关的字段)
partner models.ForeignKey(Partner)

我每个都有一个ListView,每个都有一个DetailView(工作正常)。



问题是,在Partner DetailView页面上,我有讲座列表。在许多情况下,该列表可能相当长(例如> 200),利益相关者希望它被分页。我在ListView页面上没有分页分页问题(很简单),但我似乎无法在合作伙伴的DetailView页面上找出如何在他们的讲座列表上分页。


$ b $我希望在Django文档代码中看到如下:

  class PartnerDetailView(DetailView): 
model = Partner
paginate_using =讲座#(或类似self.lecture?)
paginate_by = 20

因此,DetailView将对单个Partner对象采取行动,但是(容易地)允许从讲座FK结果中分页。



是有支持吗?或者它需要更多的自定义视图代码(可能在** kwargs中为get_context_data()创建一个page变量,并根据该变量创建子集)?



它只是看起来像是一个非常普遍的情况下CBVs,所以我很困惑为什么一个搜索没有提出任何例子。



更新:应该已经发生了我,执行此操作的简单方法是将一个页面片段添加到引用DetailView的url()条目,并使用它来创建FK对象上的分页子集。



请注意,这也可能是一个可行的方法来解决如何从FormView分页结果问题...

解决方案

你最好的选择是将ListView而不是DetailView进行子类化,并覆盖 get_queryset 以从合作伙伴获得讲座。如果需要,您也可以在 get_context_data 中添加合作伙伴对象。


Given a models.py:

class Partner(models.Model):
    ... (fields irrelevant to this example)

class Lecture(models.Model):
    ... (other fields not relevant to this example)
    partner models.ForeignKey(Partner)

I have a ListView for each and a DetailView for each (working fine).

The problem is that on the Partner DetailView page, I have the list of Lectures. In many cases this list can be quite long (e.g., >200), and the stakeholders want it to be paginated. I've had no problems with pagination on the ListView pages (that's easy), but I can't seem to figure out on the Partner's DetailView page how to paginate on their Lecture list.

I was hoping to see in the Django docs code that would look something like:

class PartnerDetailView(DetailView):
    model = Partner
    paginate_using = Lecture # (or something like self.lecture ?)
    paginate_by = 20

whereupon the DetailView would act on the single Partner object, but would (easily) allow pagination from the Lecture FK results.

Is there support for this? Or will it require far more custom view code (perhaps putting a 'page' variable in **kwargs for get_context_data() and creating the subset based on that)?

It just seems like a very common situation under CBVs so I'm puzzled why a search hasn't turned up any examples.

UPDATE: It should have occurred to me that a simple way to do this would be to just add a "page" piece to the url() entry that references the DetailView and use that to create the subset of pagination on the FK objects.

Note that this also might be a workable approach to getting around the "how do you paginate results from a FormView" issue...

解决方案

Your best bet is probably to subclass ListView rather than DetailView, and override get_queryset to get the Lectures from the Partner. You can add the Partner object in get_context_data as well if you need it.

这篇关于来自Django DetailView的分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆