1、在应用模块下,创建urls文件,用来存放访问路由
2、在项目总访问url里面注册路由
3、在view文件里,定义方法参数
from django.core import serializers
from django.db import connection
from django.http import HttpResponse, JsonResponse
# 分页
from django.core.paginator import Paginator, EmptyPage
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Q, F
from .models import Tests
def tests_list(request):
page_number = int(request.GET.get('page', 1))
search_term = request.GET.get('q', '')
# 定义每页显示的条目数
items_per_page = 10
# 构建模糊查询的Q对象
query = Q()
if search_term:
query &= (Q(name__icontains=search_term) | Q(password__icontains=search_term))
# 添加状态等于1的条件
#query &= Q(status=1)
# 计算出从哪一条数据开始查询
offset = (page_number - 1) * items_per_page
# 应用模糊查询获取过滤后的数据
filtered_users = Tests.objects.filter(query).order_by('-id')[offset:offset + items_per_page]
# 获取过滤后的总条目数
total_items = Tests.objects.filter(query).count()
# 计算总页数
total_pages = (total_items + items_per_page - 1) // items_per_page
# 执行查询,只获取当前页的数据
page_obj = filtered_users
json_data = [user.to_dict() for user in page_obj]
# print(user_data)
# user_data = User.objects.all()
# json_data = [ user.to_dict() for user in user_data]
# 带上条件过滤数据
# user_data = User.objects.filter(name='222333')
# print(user_data)
# list_of_dicts = list(user_data.values())
# json_data = json.dumps(list_of_dicts, cls=DjangoJSONEncoder)
return JsonResponse({'data': json_data, 'total': total_items, 'total_pages': total_pages}, safe=False)
def tests_add(request):
pass
def tests_edit(request):
pass
def tests_delete(request):
pass