gpt4 book ai didi

python - 如何从多个上下文对象中选择 get_context_data 进行分页?

转载 作者:行者123 更新时间:2023-12-01 07:48:09 24 4
gpt4 key购买 nike

我试图通过从多个上下文对象中进行选择来对views.py 中的get_context_data 进行分页。代码示例条件语句中只显示了两个选择,但我还有几个选择,基本上涵盖了表单提交的所有选择。然而,最终只返回一个上下文,将上下文传递给模板 View 进行分页。

我也尝试在settings.py中全局设置分页,但它不起作用。

我之前已经看过下面的文章,作为 get-context-objects 分页指南。

How to perform pagination for context object in django?

来自views.py:

from django.shortcuts import render
import django.views.generic
from django.http import HttpResponse
from django.template import loader
from django.template import RequestContext
from ephemera.models import *
from ephemera.serializers import ItemSerializer
from rest_framework import generics
from ephemera.forms import SearchForm, AdvSearchForm
from itertools import chain
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger



class SearchResultsAdvancedView(django.views.generic.ListView):
template_name = 'ephemera/searchresults_advanced.html'
form = AdvSearchForm()
paginate_by = 10
model = Item

def get_context_data(self, **kwargs):
context = super(SearchResultsAdvancedView, self).get_context_data(**kwargs)

choose_collection = self.request.GET.get('choose_collection')
user_input = self.request.GET.get('user_input')
choose_item = self.request.GET.get('choose_item')

bookpage = False
imagepage = False

if choose_collection == 'All' and user_input == '' and choose_item == 'book':
context['book_qs'] = Item.objects.raw('SELECT * FROM ephemera_item WHERE ephemera_item.material_type LIKE %s', ['book']);
bookpage = True
elif choose_collection == 'All' and user_input == '' and choose_item == 'image':
context['image_qs'] = Item.objects.raw('SELECT * FROM ephemera_item WHERE ephemera_item.material_type LIKE %s', ['image']);
imagepage = True

if bookpage:
paginator = Paginator(context, self.paginate_by)
page = self.request.GET.get('page')
try:
book_qs = paginator.page(page)
except PageNotAnInteger:
book_qs = paginator.page(1)
except EmptyPage:
book_qs = paginator.page(paginator.num_pages)
context['book_qs'] = book_qs

elif imagepage:
paginator = Paginator(context, self.paginate_by)
page = self.request.GET.get('page')
try:
image_qs = paginator.page(page)
except PageNotAnInteger:
image_qs = paginator.page(1)
except EmptyPage:
image_qs = paginator.page(paginator.num_pages)
context['image_qs'] = image_qs

return context

返回的错误包括:

异常值:不可散列类型:'sl​​ice'

异常位置:页面中的 c:\users\administrator\appdata\local\programs\python\python36-32\lib\site-packages\django\core\paginator.py,第 70 行

最佳答案

无需使用get_context_data [Django-doc]在这里,您可以覆盖 get_queryset [Django-doc]get_context_object_name [Django-doc]确定模板中列表的名称:

class SearchResultsAdvancedView(django.views.generic.ListView): 
template_name = 'ephemera/searchresults_advanced.html'
form = AdvSearchForm()
paginate_by = 10
model = Item

def item_type(self):
choose_collection = self.request.GET.get('choose_collection')
if choose_collection != 'All' or not self.request.GET.get('user_input'):
return None
choose_item = self.request.GET.get('choose_item')
if choose_item in ('book', 'image'):
return choose_item
return None

def <b>get_queryset</b>(self, *args, **kwargs):
item_type = self.get_item_type()
qs = super.get_queryset(*args, **kwargs)
if item_type is not None:
return qs.filter(material_type__iexact=item_type)
return qs.none()

def <b>get_context_object_name</b>(self, object_list):
item_type = self.get_item_type()
if item_type is not None:
return '{}_qs'.format(item_type)
return super().get_context_object_name(object_list)

Django 的逻辑将对 QuerySet 本身进行分页,因此您无需担心这一点。这是由于get_context_data [Django-doc]实现MultipleObjectMixin [Django-doc] :

def get_context_data(self, *, object_list=None, **kwargs):
"""Get the context for this view."""
queryset = object_list if object_list is not None else self.object_list
page_size = self.get_paginate_by(queryset)
context_object_name = self.get_context_object_name(queryset)
if page_size:
<b>paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)</b>
context = {
'paginator': paginator,
'page_obj': page,
'is_paginated': is_paginated,
'object_list': queryset
}
else:
context = {
'paginator': None,
'page_obj': None,
'is_paginated': False,
'object_list': queryset
}
if context_object_name is not None:
context[context_object_name] = queryset
context.update(kwargs)
return super().get_context_data(**context)

话虽如此,我的印象是建模做得不太好。如果您有项目类型,则定义 ItemType 模型是有意义的。此外,您最好使用 Django 的 ORM 来生成查询,而不是原始查询。

关于python - 如何从多个上下文对象中选择 get_context_data 进行分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56349464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com