用django写一段带分页和检索功能的增删改查代码
时间: 2024-05-13 16:15:52 浏览: 94
好的,下面是基于 Django 的增删改查代码,包含分页和检索功能。
首先,我们需要在 `models.py` 中定义一个模型:
```python
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
description = models.TextField()
published_date = models.DateField()
def __str__(self):
return self.title
```
接下来,在 `views.py` 中定义视图函数:
```python
from django.shortcuts import render, redirect
from django.core.paginator import Paginator
from .models import Book
def book_list(request):
books = Book.objects.all()
# 分页功能实现
paginator = Paginator(books, 10)
page = request.GET.get('page')
books_page = paginator.get_page(page)
# 检索功能实现
query = request.GET.get('q')
if query:
books_page = Book.objects.filter(title__icontains=query)
return render(request, 'book_list.html', {'books': books_page})
def book_create(request):
if request.method == 'POST':
title = request.POST.get('title')
author = request.POST.get('author')
description = request.POST.get('description')
published_date = request.POST.get('published_date')
Book.objects.create(title=title, author=author, description=description, published_date=published_date)
return redirect('book_list')
return render(request, 'book_create.html')
def book_update(request, pk):
book = Book.objects.get(pk=pk)
if request.method == 'POST':
book.title = request.POST.get('title')
book.author = request.POST.get('author')
book.description = request.POST.get('description')
book.published_date = request.POST.get('published_date')
book.save()
return redirect('book_list')
return render(request, 'book_update.html', {'book': book})
def book_delete(request, pk):
book = Book.objects.get(pk=pk)
book.delete()
return redirect('book_list')
```
在上述代码中,我们定义了 `book_list()` 函数来显示所有的书籍,并且实现了分页和检索功能。其中,分页功能使用了 Django 内置的 `Paginator` 类,检索功能使用了 Django 的查询操作 `filter()` 和 `icontains`。
我们还定义了 `book_create()`、`book_update()` 和 `book_delete()` 函数来实现增、删、改功能。
最后,在 `urls.py` 中将视图函数与 URL 路径关联起来:
```python
from django.urls import path
from .views import book_list, book_create, book_update, book_delete
urlpatterns = [
path('', book_list, name='book_list'),
path('create/', book_create, name='book_create'),
path('update/<int:pk>/', book_update, name='book_update'),
path('delete/<int:pk>/', book_delete, name='book_delete'),
]
```
以上就是基于 Django 的增删改查代码,包含分页和检索功能的实现。
阅读全文