【发布时间】:2017-01-14 23:33:14
【问题描述】:
假设,我想建立一个论坛,实现Thread 和Comment 概念。Comment 模型是ForeignKey 到Thread。
class Thread(models.Model):
title = models.CharField(max_length=200)
....
class Comment(models.Model):
thread = models.ForeignKey(Thread, ...)
comment = models.TextField()
....
- 详细讨论帖有一些评论
-
详情线程的评论使用
/?page={number}进行分页。
目前,我的 cmets 分页运行良好。但是,如果我想找到一个评论对象,我就有问题了。
例如,我在page=3 中找到了带有id=13 的单个评论对象。
这是我的views.py
def thread_detail(request, topic_slug, pk):
"""
detail thread public view.
:param `topic_slug` is slug from the topic.
:param `pk` is id from thread.
"""
template_name = 'public/thread_detail.html'
numb_pages = 10
get_page = request.GET.get('page')
thread = get_object_or_404(Thread, topic__slug=topic_slug, pk=pk)
comments = Comment.objects.filter(thread=thread).order_by('created')
....
page_obj = PaginatorFBV(comments, numb_pages, get_page).queryset_paginated()
page_range = PaginatorFBV(comments, numb_pages, get_page).page_numbering()
comments = page_obj.object_list
context = {
'thread': thread,
'comments': comments,
'page_obj': page_obj,
'page_range': page_range
}
return render(request, template_name, context)
我想动态创建它,例如在我的find_comment_view.py:
def find_comment(request, pk):
"""
Return redirect to the comment on thread, with current page.
:param `pk` is pk/id from comment.
"""
comment = get_object_or_404(Comment, pk=pk)
comments = Comment.objects.filter(thread__in=comment.thread)
# what i should be do here?
之前非常感谢..
更新:
我试试这个,效果很好。 但是,如果页面很多,我发现另一个问题,例如;几千页..当然需要很长时间...
def find_comment(request, pk):
"""
Return redirect to the comment on thread, with current page.
:param `pk` is pk/id from comment.
"""
comment = get_object_or_404(Comment, pk=pk)
comments = Comment.objects.filter(thread=comment.thread).order_by('created')
thread = get_object_or_404(Thread, pk=comment.thread.pk)
# Initial `page_obj` to get max numb of pagination.
items_per_page = 10 # this is same with what we do for `numb_pages = 10` inside `def thread_detail(...)`
initial_page_obj = PaginatorFBV(comments, items_per_page, 1).queryset_paginated()
max_numb_pages = initial_page_obj.paginator.num_pages
for page in range(max_numb_pages):
page += 1
page_obj = PaginatorFBV(comments, items_per_page, page).queryset_paginated()
comment_objects = page_obj.object_list
# Check the output of `comment_objects`
# >>> print(comment_objects, page)
# <QuerySet [<Comment: regina>]> 1
# <QuerySet [<Comment: beverly>]> 2
# <QuerySet [<Comment: amy>]> 3
# <QuerySet [<Comment: hannah>]> 4
for obj in comment_objects:
if obj.pk == comment.pk:
# eg: /thread/20/?page=2#comment-30
return redirect(
('%s?page=%s#comment-%s') % (
thread.get_absolute_url(),
page, comment.pk
)
)
return redirect(('%s#comment-%s') % (thread.get_absolute_url(), comment.pk))
在urls.py内部
urlpatterns = [
....
url(
r'^comment/direct/(?P<pk>[-\d]+)/$',
find_comment, name='find_comment_page'
),
]
【问题讨论】:
标签: python django pagination