1:序列化获取数据的接口设计
1:分页获取序列化数据 2:是个能传参数的接口
class Society(APIView): def post(self, request):
keywords = str(request.data.get("keywords"))
data = {}
try:
s_data = models.Society.objects.filter(name__contains=keywords).order_by('id') # 模糊查询 pg = PageNumberPagination()
pg.max_page_size = 200
pg.page_size_query_param = "size"
pager_roles = pg.paginate_queryset(queryset=s_data, request=request, view=self)
ser = PagerSerialiser(instance=pager_roles, many=True)
data["code"] = 200
data["count"] = len(s_data) # 获取总数量
data["data"] = ser.data
return Response(data)
except Exception as e:
data["code"] = 444
data["message"] = "请求异常"
return JsonResponse(data)
2:前端代码的设计
1:创建2个关键词keywords_raw,keywords,当没有使用搜索功能时,我们传上去的是keywords,它是空值,所以接口会返回给我们所有的数据,分页请求的keywords也是空值,所以这个时候的请求数据是所有的 2:当我们在输入框上输入了关键词keywords_raw,点击时,这个时候将keywords_raw的值赋值给keywords,这样子去请求就可以做到搜索关键词后的分页点击是属于搜索关键词的数据 代码: HTML:
<input type="text" class="form-control" placeholder="输入关键词查找社团" v-model="keywords_raw"> <button @click="search"> 搜索</button> JS: data:{
keywords_raw: "",
keywords: "",
} // 钩子函数渲染数据
created() {
// 数据渲染
axios.post('/society/get/?page=1&size=6', {
keywords: this.keywords # 上传的参数是keywords 这个时候还是空值,请求的数据是所有的
}).then(response => {
this.totals = parseInt(response.data.count)
response.data.data.some((item, i) => {
this.society_data.unshift({
societHead: item.head,
societUser: item.user,
societName: item.name,
societMember: item.member,
societTime: item.time.substring(0, 10),
pk: item.id,
})
})
}).catch(error => {
alert("请重新登录")
window.location.href = '/login/'
})
} // 搜索:
// search
search() {
if ( this.keywords_raw == "") {
alert("输入框不能为空")
} else {
this.society_data =[]
// 请求的时候赋值给keywords
this.keywords =this.keyword_raw # 直接同步两个参数
axios.post('/society/get/?page=1&size=6', {
keywords: this.keywords_raw
}).then(response => {
this.totals = parseInt(response.data.count)
response.data.data.some((item, i) => {
this.society_data.unshift({
societHead: item.head,
societUser: item.user,
societName: item.name,
societMember: item.member,
societTime: item.time.substring(0, 10),
pk: item.id, })
})
}).catch(error => {
console.log(error) })
}
} // 分页
handleSizeChange(val) {
console.log(`每页 ${val} 条`);
},
handleCurrentChange(val) { this.society_data = [],
axios.post('/society/get/?page=' + val + '&size=6', {
keywords: this.keywords # 上传的是参数是关键词
}).then(response => {
this.totals = parseInt(response.data.count)
response.data.data.some((item, i) => {
this.society_data.unshift({
societHead: item.head,
societUser: item.user,
societName: item.name,
societMember: item.member,
societTime: item.time.substring(0, 10),
pk: item.id, })
})
}).catch(error => {
console.log(error) })
},
3:效果图