如果对django rest尚未了解,建议看官方的Quickstart,https://www.django-rest-framework.org/tutorial/quickstart/,也有中文版 https://www.django.cn/course/show-19.html
简单来说,使用Django REST framework需要涉及4个关键类。
model:模型,定义数据表
sariaizers:序列化,相当于form
viewsets:视图
router:路由器,注册url地址
如果已经存在表结构,可以使用python命令反向生成类文件,python manage.py inspectdb > d:\model.py,从生成文件中copy对应表的代码
from django.db import models
class SysUsers(models.Model):
SEX_TYPE = (
("1", "男"),
("0", "女"),
)
name = models.TextField(blank=True, null=True)
sex = models.CharField(blank=True, default='1', choices=SEX_TYPE)
age = models.IntegerField()
create_time = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'sys_users'
from rest_framework import serializers
# 列表序列化类,仅展示部分字段
class SysUsersSerializer(serializers.ModelSerializer):
name = serializers.CharField()
sex = serializers.SerializerMethodField()
age= serializers.CharField()
create_time = serializers.CharField()
class Meta:
# 定义关联的 Model
model = SysUsers
# 指定返回的 fields
# fields = ['id', 'name', 'sex', 'age', 'create_time']
fields = '__all__'
def get_sex(self, obj):
return obj.get_sex_display()
ModelViewSet类是高级类,默认提供方法:.list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy()
class SysUsersViewSet(viewsets.ModelViewSet):
# Because ModelViewSet extends GenericAPIView,
# you'll normally need to provide at least the queryset and serializer_class attributes
serializer_class = SysUsersSerializer
queryset = SysUsers.objects.all()
pagination_class = SysUsersPagination
# 查询条件,过滤数据
def filter_queryset(self, queryset):
params = self.request.query_params
name= params.get('name')
sex = params.getlist('sex[]')
if name and len(name) > 0:
queryset = queryset.filter(name__contains=name)
if sex and len(sex) > 0:
q = Q()
for p in platform:
q = q | Q(sex=p)
queryset = queryset.filter(q)
return queryset
from rest_framework.pagination import PageNumberPagination
class SysUsersPagination(PageNumberPagination):
page_size = 10
# 前台通过传递该参数可调整每页返回数据数量
page_size_query_param = 'page_size'
在项目的urls.py文件中,写入:
router.register('sys/users', SysUsersViewSet, basename='sys_users')
以上完成后,启动服务(python manage.py runserver),浏览器中查看效果。。。
前台传递多个主键,使用 in 批量更新的写法,如下:
# 获取数据
data = self.request.data
ids = data['ids'] # 主键
age=data['age']
# 获取符合要求的对象
qs = SysUsers.objects.filter(id__in=ids)
# 更新年龄字段
qs.update(age=age)