分页样式可以使用 DEFAULT_PAGINATION_CLASS 和 PAGE_SIZE setting key 全局设置。例如,要使用内置的 page_size/page 分页,你可以这样做:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
配置文件
"""
Django settings for day14 project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ')y%g&-ia8zx3(f32e1t-1^xsm$+_u_a)0=5a!4u9zel1l*i@rg'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'App.apps.AppConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'day14.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'day14.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'day11',
'HOST': '127.0.0.1',
'USER': 'root123',
'PASSWORD': '123456',
'PORT': 3306
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 4 # 每页数目
}
url
from App import views
from django.urls import path
app_name = "App"
urlpatterns = [
path('book/', views.BookListView.as_view(), name='book'),
]
model
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models
class User(models.Model):
uid = models.AutoField(primary_key=True)
username = models.CharField(unique=True, max_length=30)
password = models.CharField(max_length=120)
regtime = models.DateTimeField()
sex = models.IntegerField(blank=True, null=True)
is_active = models.IntegerField(blank=True, null=True)
class Meta:
managed = True
db_table = 'user'
class Bookinfo(models.Model):
btitle = models.CharField(max_length=200)
bpub_date = models.DateField(blank=True, null=True)
bread = models.IntegerField()
bcomment = models.IntegerField()
bimage = models.CharField(max_length=200, blank=True, null=True)
class Meta:
managed = True
db_table = 'bookinfo'
# 对象转字典,建立一个类对象的一个方法
def obj_to_dict(self):
return {
'btitle': self.btitle,
'bpub_date': self.bpub_date,
'bread': self.bread,
'bcomment': self.bcomment,
'bimage': self.bimage
}
class Heroinfo(models.Model):
hid = models.AutoField(primary_key=True)
hname = models.CharField(max_length=50)
book = models.ForeignKey(Bookinfo, models.CASCADE, db_column='bid', blank=True, null=True, related_name='heros')
class Meta:
managed = True
db_table = 'heroinfo'
def __str__(self):
return self.hname
view
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView, ListAPIView
# Create your views here.
from rest_framework.pagination import PageNumberPagination
from App.models import Bookinfo
from App.serializers import BookinfoSerializer
PageNumberPagination.page_size_query_param = 'page_size'
class BookListView(ListAPIView):
queryset = Bookinfo.objects.all()
serializer_class = BookinfoSerializer
pagination_class = PageNumberPagination
# return Response({'code': 1})
# def get(self, request, *args, **kwargs):
# # 得到分页对象
# pagenation = self.pagination_class()
# # pagenation.page_size = 2 每页数目
# # pagenation.page_query_param = 'page' # 路由中?后面的key,指定页码
# # pagenation.page_size_query_param = 'size' # 指定当前页显示多少条
# # pagenation.max_page_size = 3 前端最多能设置的每页数量
# # page_queryset = pagenation.paginate_queryset(self.queryset, request)
# #
# # serializer = self.BookinfoSerializer(instance=page_queryset, many=True)
# # response = pagenation.get_paginated_response(serializer.data)
# # print(response.data)
# page_queryset = pagenation.paginate_queryset(self.queryset, request)
自定义
MyPagination.py
from rest_framework.pagination import PageNumberPagination
class BookListPager(PageNumberPagination):
page_size = 5 # 每页5条记录
page_size_query_param = 'page_size' # 每页记录数的参数名字
目录结构