django实现增删改查分页接口

django实现增删改查分页接口(小白必备)

在上篇文章中我使用nodejs实现了增删改查分页接口,这一篇我们则使用django实现。

1.创建一个django项目,命令如下
python manage.py startapp myapp

2.在你自己的myapp文件夹中的models.py中定义你们自己的模型

from django.db import models

class 名字(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)

3.迁移数据库,创建模型的数据表,通过以下两行命令

python manage.py makemigrations
python manage.py migrate

4.在myapp文件夹中的views.py文件中编写处理请求

from django.core.paginator import Paginator
from django.http import JsonResponse
from myapp.models import Book

def get_books(request):
    # 获取所有书籍
    books = Book.objects.all()

    # 分页
    paginator = Paginator(books, 10) # 每页显示10条记录
    page_number = request.GET.get('page') # 获取页码参数
    page_obj = paginator.get_page(page_number)

    # 构造返回数据
    data = {
        'current_page': page_obj.number,
        'total_pages': paginator.num_pages,
        'books': [
            {'title': book.title, 'author': book.author, 'publication_date': str(book.publication_date)}
            for book in page_obj.object_list
        ]
    }

    return JsonResponse(data)

def create_book(request):
    # 获取POST请求数据
    title = request.POST.get('title')
    author = request.POST.get('author')
    publication_date = request.POST.get('publication_date')

    # 创建书籍对象并保存
    book = Book(title=title, author=author, publication_date=publication_date)
    book.save()

    return JsonResponse({'message': 'Book created successfully'})

def update_book(request, book_id):
    # 获取PUT请求数据
    title = request.PUT.get('title')
    author = request.PUT.get('author')
    publication_date = request.PUT.get('publication_date')

    # 更新书籍对象
    book = Book.objects.get(id=book_id)
    book.title = title
    book.author = author
    book.publication_date = publication_date
    book.save()

    return JsonResponse({'message': 'Book updated successfully'})

def delete_book(request, book_id):
    # 删除书籍对象
    book = Book.objects.get(id=book_id)
    book.delete()

    return JsonResponse({'message': 'Book deleted successfully'})

5.在项目的urls.py文件中配置URL路由

from django.urls import path
from myapp.views import get_books, create_book, update_book, delete_book

urlpatterns = [
    path('books/', get_books),
    path('books/create/', create_book),
    path('books/update//', update_book),
    path('books/delete//', delete_book),
]

6.运行项目

python manage.py runserver

到这里也就结束了,希望对您有所帮助。

django实现增删改查分页接口_第1张图片

你可能感兴趣的:(django,sqlite,数据库,python)