按许多对象 django 分页
paginate by a number of objects django
所以即使没有从模板启动 django-filters 分页也不起作用,我无法按我想要的对象数量分页,它一次显示所有对象
*注意:我并不是说两者应该一起工作(分页和 django-filter),只是我想修复分页
views.py
def music_page(request):
#pagination & filter
music = Music.objects.all().order_by('-id')
music_filter = MusicFilter(request.GET, queryset=music)
paginator = Paginator(music, 6)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
try:
music = paginator.page(page_number)
except PageNotAnInteger:
music = paginator.page(1)
except EmptyPage:
music.paginator.page(paginator.num_pages)
return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter})
模板
<div class='card'>
{% for m in filter.qs %}
<div class='year'>{{m.Year}}</div>
<div class='song_name'>{{m.song}}</div>
{% endfor %}
</div>
首先,您没有传入正确的查询集。您需要传入过滤后的查询集而不是音乐。
music = Music.objects.all().order_by('-id')
music_filter = MusicFilter(request.GET, queryset=music)
filtered_music = music_filter.qs
paginator = Paginator(filtered_music, 6)
然后在您的模板中,您必须遍历此 page_obj
以获取您的对象。
<div class='card'>
{% for m in page_obj %}
<div class='year'>{{m.Year}}</div>
<div class='song_name'>{{m.song}}</div>
{% endfor %}
</div>
所以即使没有从模板启动 django-filters 分页也不起作用,我无法按我想要的对象数量分页,它一次显示所有对象
*注意:我并不是说两者应该一起工作(分页和 django-filter),只是我想修复分页
views.py
def music_page(request):
#pagination & filter
music = Music.objects.all().order_by('-id')
music_filter = MusicFilter(request.GET, queryset=music)
paginator = Paginator(music, 6)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
try:
music = paginator.page(page_number)
except PageNotAnInteger:
music = paginator.page(1)
except EmptyPage:
music.paginator.page(paginator.num_pages)
return render(request, template_name='main/music.html', context={'music': music, 'page_obj': page_obj, 'filter': music_filter})
模板
<div class='card'>
{% for m in filter.qs %}
<div class='year'>{{m.Year}}</div>
<div class='song_name'>{{m.song}}</div>
{% endfor %}
</div>
首先,您没有传入正确的查询集。您需要传入过滤后的查询集而不是音乐。
music = Music.objects.all().order_by('-id')
music_filter = MusicFilter(request.GET, queryset=music)
filtered_music = music_filter.qs
paginator = Paginator(filtered_music, 6)
然后在您的模板中,您必须遍历此 page_obj
以获取您的对象。
<div class='card'>
{% for m in page_obj %}
<div class='year'>{{m.Year}}</div>
<div class='song_name'>{{m.song}}</div>
{% endfor %}
</div>