Django Restframework

安装:

pip install djangorestframework

 

开始使用序列化
1. 导入模块
2. 建立一个序列化类
3. 获取queryset
4. 开始序列化
5. 获取序列化后的数据,返回给客户端

from rest_framework import serializers
from Reim.models import Users,Dept,Roles,Menus
#创建序列化类,字段类型不一定要跟models的字段一致
class UserSerializer(serializers.Serializer):
    id=serializers.CharField(max_length=10,read_only=True)
    name=serializers.CharField(max_length=12)
    username = serializers.CharField(max_length=24)
    pwd = serializers.CharField(max_length=24)
    # roleuser = serializers.CharField(max_length=24)#对多对多字段
    sort = serializers.CharField(max_length=24)
    dept = serializers.CharField(max_length=24)
    # dept_id = serializers.CharField(max_length=24,source="dept.id")
    # dept_name = serializers.CharField(max_length=24,source="dept.name",read_only=True)

    roleuser = serializers.SerializerMethodField()#对多对多字段 默认read_only=True
    def get_roleuser(self,obj):
        role_list=list()
        for role in obj.roleuser.all():
            role_list.append({"id":role.id,"name":role.name})
        return role_list

    def create(self, validated_data):
        # 关键词替换    用来处理一对多

        print(validated_data)
        validated_data["dept_id"]=validated_data.pop("dept")
        print(validated_data)
        usr_obj=Users.objects.create(**validated_data)
        return usr_obj  

  

 

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   serializers.py
@Contact :   shuishandt@foxmail.com
@License :   (C)Copyright 2019-2020, Liugroup-NLPR-CASIA
 
@修改日期          @作者      @版本      @描述
------------      -------    --------    -----------
2019/11/23 9:17   gxrao      1.0         None
'''
 
from rest_framework import serializers
from Reim.models import Users,Dept,Roles,Menus
#创建序列化类,字段类型不一定要跟models的字段一致
'''
class UserSerializer(serializers.Serializer):
    id=serializers.CharField(max_length=10,read_only=True)
    name=serializers.CharField(max_length=12)
    username = serializers.CharField(max_length=24)
    pwd = serializers.CharField(max_length=24)
    # roleuser = serializers.CharField(max_length=24)#对多对多字段
    sort = serializers.CharField(max_length=24)
    dept = serializers.CharField(max_length=24)
    # dept_id = serializers.CharField(max_length=24,source="dept.id")
    # dept_name = serializers.CharField(max_length=24,source="dept.name",read_only=True)
 
    roleuser = serializers.SerializerMethodField()#对多对多字段 默认read_only=True
    def get_roleuser(self,obj):
        role_list=list()
        for role in obj.roleuser.all():
            role_list.append({"id":role.id,"name":role.name})
        return role_list
 
    def create(self, validated_data):
        # 关键词替换    用来处理一对多
 
        print(validated_data)
        validated_data["dept_id"]=validated_data.pop("dept")
        print(validated_data)
        usr_obj=Users.objects.create(**validated_data)
        return usr_obj
'''
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model=Users
        fields="__all__"
        #只写字段
        # extra_kwargs={
        #     'dept':{'write_only':True},
        #     'roleuser': {'write_only': True}
        # }
 
 
    dept_id = serializers.CharField(max_length=24,source="dept.id",read_only=True)
    dept_name = serializers.CharField(max_length=24,source="dept.name",read_only=True)
 
    roleuser = serializers.SerializerMethodField()#对多对多字段 默认read_only=True
    def get_roleuser(self,obj):
        role_list=list()
        for role in obj.roleuser.all():
            role_list.append({"id":role.id,"name":role.name})
        return role_list
"""
    def create(self, validated_data):
        # 关键词替换    用来处理一对多    默认会写好
 
        print(validated_data)
        # validated_data["dept_id"]=validated_data.pop("dept")
        print(validated_data)
        usr_obj=Users.objects.create(**validated_data)
        return usr_obj
 
"""
 
 
 
from django.shortcuts import render
 
from rest_framework.views import APIView
from rest_framework.response import Response
 
from Reim.models import Users,Dept,Menus,Roles
from utils.serializers import UserSerializer
# Create your views here.
 
 
class UserView(APIView):
    def get(self,request):
        origin_data=Users.objects.all()
 
        serialized_data=UserSerializer(origin_data,many=True)#查询是多行数据,many=True
        return Response(serialized_data.data)
 
 
    def post(self,request):
        get_data=request.data
        verified_data=UserSerializer(data=get_data,many=False)
 
        if verified_data.is_valid():
            user_obj=verified_data.save()
            # 用来处理多对多
            roleusers=Roles.objects.filter(id__in=request.data['roleuser'])
            print(">>>>>>>>>>>>>>>>>>>",roleusers)
            user_obj.roleuser.add(*roleusers)
            return Response(verified_data.data)
        else:
            return Response(verified_data.errors)
 
 
class UserView(ListModelMixin,CreateModelMixin,GenericAPIView):
    queryset = Users.objects.all()
    serializer_class = UserSerializer
    def get(self,request,*args,**kwargs):
        return self.list(request,*args,**kwargs)
 
    def post(self,request,*args,**kwargs):
        return self.create(request,*args,**kwargs)
 
11/24
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.mixins import (
    ListModelMixin,CreateModelMixin,DestroyModelMixin,UpdateModelMixin,RetrieveModelMixin
)
from rest_framework.generics import GenericAPIView
from rest_framework import generics
from rest_framework.viewsets import ModelViewSet
 
 
 
 
class UserFilterView(RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView):
    queryset = Users.objects.all()
    serializer_class = UserSerializer
 
    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)
    def delete(self,request,*args,**kwargs):
        return self.destroy(request,*args,**kwargs)
    def put(self,request,*args,**kwargs):
        return self.update(request,*args,**kwargs)
 
 
class UserView(generics.ListCreateAPIView):
    queryset = Users.objects.all()
    serializer_class = UserSerializer
 
 
class UserFilterView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Users.objects.all()
    serializer_class = UserSerializer
'''
class UserView(ModelViewSet):
    queryset = Users.objects.all()
    serializer_class = UserSerializer
 
 
  urlpatterns = [
    # re_path(r'v1/user/$', views.UserView.as_view()),
    # re_path(r'v1/user/(?P<pk>\d+)/$', views.UserFilterView.as_view()),
    re_path(r'v1/user/$',views.UserView.as_view({
        'get':'list',
        'post':'create',
    })),
    re_path(r'v1/user/(?P<pk>\d+)/$', views.UserView.as_view({
        'get':'retrieve',
        'put':'update',
        'delete':'destroy',
    })),
 
]
posted @ 2019-11-10 15:25  巨兽~墨菲特  阅读(129)  评论(0编辑  收藏  举报