如果用户有一个相关的Profile模型,带有一个字段,例如:
from django.conf import settings
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
paginate_by = models.PositiveIntegerField(default=10)
# …
您可以覆盖.get_paginate_by(..) method [Django-doc]:
class CandidateListView(LoginRequiredMixin, ListView):
template_name = 'recruiter/candidate_list.html'
context_object_name = 'candidates'
def get_paginate_by(self, queryset):
return self.request.user.profile.paginate_by
如果.profile 不存在,将try-except 包装起来可能更安全:
class CandidateListView(LoginRequiredMixin, ListView):
template_name = 'recruiter/candidate_list.html'
context_object_name = 'candidates'
paginate_by = 20
def get_paginate_by(self, queryset):
try:
return self.request.user.profile.paginate_by
except Profile.DoesNotExist:
return super().get_paginate_by(queryset)
当该用户的个人资料不存在时,您将回退到 20。
如果不想对结果进行分页,可以返回None。