restful

1.分页

修改settings.py配置文件, 增加分页的配置信息

1
2
3
4
5
6
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 2,
'DEFAULT_RENDERER_CLASSES': (
'utils.functions.CustomJsonRenderer',
),
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
"code": 0,
"msg": "请求成功",
"data": {
"count": 1,
"next": null,
"previous": null,
"results": [
{
"s_name": "瑶瑶",
"s_yuwen": 88,
"g": 1,
"id": 3,
"g_name": "python1"
}
]
}
}

注意: 在结果在data对应的value值中, 有一个count的key, 表示返回数据有1条, next表示下一个的url, pervious表示上一页的url

2.过滤

修改settings.py配置文件, 增加filter过滤的信息

2.1安装过滤的库
1
pip install django-filters
2.2配置settings.py的信息

配置DEFAULT_FILTR_BANNCKENDS

1
2
3
4
5
6
7
8
9
10
11
12
REST_FRAMEWORK = {
# 分页显示
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 2,
# 配置过滤
'DEFAULT_FILTER_BACKENDS': (
'rest_framework.filters.DjangoFilterBackend',
'rest_framework.filters.SearchFilter'),
'DEFAULT_RENDERER_CLASSES': (
'utils.functions.CustomJsonRenderer',
),
}
2.3views中指定filter_class
1
2
3
4
5
6
7
8
9
10
11
12
13
class api_student(mixins.ListModelMixin,
mixins.UpdateModelMixin,
mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):

# 学生的所有信息
queryset = Student.objects.all().filter(delete=False)
# 序列化学生的所有信息(表现层, 将数据按照一定格式返回给用户)
serializer_class = StudentSerializer
# 过滤
filter_class = StudentFilter
2.4编写filter_class过滤信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import django_filters
from rest_framework import filters

from app.models import Student


class StudentFilter(filters.FilterSet):
# 模糊查询学生的s_name姓名
s_name = django_filters.CharFilter('s_name', lookup_expr='contains')
# 查询语文成绩大于80分的学生
s_yuwen = django_filters.NumberFilter('s_yuwen', lookup_expr='gte')
s_yuwen_max = django_filters.NumberFilter('s_yuwen', lookup_expr='lte')

class Meta:
model = Student
fields = ['s_name', ]
2.5实现方法
2.5.1查询学生的姓名中包含瑶的学生

使用filter_class进行过滤筛选 :

1
http://127.0.0.1:8080/stu/student/?name=瑶

不使用filter_class进行筛选:

1
2
3
def get_queryset(self):
query = self.queryset
return query.filter(s_name__contaions='瑶')
2.5.2查询学生的创建时间在2018年5月1日到2018年6月1日的学生信息

使用filter_class进行过滤筛选:

1
http://127.0.0.1:8080/stu/student/?create_min=2018-05-01&create_max=2018-06-01

不使用filter_class进行筛选:

1
2
3
4
def get_queryset(self):
query = self.queryset
return query.filter(s_create_time__gte='2018-05-01',
s_create_time__lte='2018-06-01')
2.53查询状态为休学的学生信息
1
http://127.0.0.1:8080/stu/student/?status=LEAVE_SCH
2.5.4查询所有的学生, 按照id从大到小排序
1
2
3
def get_queryset(self):
query = self.queryset
return query.order_by('-id')

最后更新: 2018年06月01日 20:06

原始链接: http://yoursite.com/2018/06/01/restful的使用/

× 请我吃糖~
打赏二维码