当前位置: 首页 > 工具软件 > ApiView > 使用案例 >

ApiView 的使用

林运浩
2023-12-01

1.APIview使用、

https://www.cnblogs.com/xiaonq/p/10124104.html
ModelVIewSet 是对 APIView 封装
ModelSerializer 是对 Serializer

  • 1.1 在 user/urls.py 中添加路由
    urlpatterns = [ path(‘apiview/’, views.UserInfoViewSet.as_view()), ]

  • 1.2 创建user/serializers.py写序列化器

serializers.ModelSerializer 和 serializers.Serializer field参数说明

#创建user/serializers.py写序列化器

class User(AbstractUser):

# phone = models.CharField(‘手机号’,max_length=20)
  # img = models.ImageField(upload_to=‘user’,null=True)
  # nick_name = models.CharField(‘昵称’,max_length=20)
  # address = models.CharField(‘地址’,max_length=255)
class UserInfoSerializer(serializers.Serializer):
  id = serializers.CharField(read_only=True) # 普通字段,设置id为只读字段,不能修改
  username = serializers.CharField(min_length=3,max_length=20,error_messages=
{‘required’: ‘该字段必填’}) # 显示普通字段
  img = serializers.ImageField(required=False)
  nick_name = serializers.CharField(max_length=20)
  address = serializers.CharField(max_length=255)
  xxx = serializers.SerializerMethodField(read_only=True) # 自定义显示(显示多对
多)
  class Meta:
    model = User

自定义显示 多对多 字段

def get_xxx(self,row):
  ‘’‘row: 传过来的正是 User表的对象’’’
  users = row.username # 获取用户名
  return users

定义创建语法:ser.save()执行,就会立刻调用create方法用来创建数据

def create(self, validated_data):
  ‘’‘validated_data: 表单或者vue请求携带的json:
{“username”:“zhangsan”,“password”:“123456”}’’’
  # https://www.cnblogs.com/xiaonq/p/7978409.html
  return User.objects.create(**validated_data)

定义更新方法

def update(self, instance, validated_data):
  ‘’’
  instance : 查询的对象
  validated_data : postman提交的json数据
  {“username”:“zhangsan”,“password”:“123456”}
  ‘’’
  if validated_data.get(‘username’):
    instance.username = validated_data[‘username’]
  instance.save()
  return instance

定义单一字段验证的方法

def validate_name(self, value):
  if value == ‘root’:
    raise serializers.ValidationError(‘不能创建root管理员账号’)
  return value

定义多字段验证方法

def validate(self, attrs):
  print(attrs)
  if attrs.get(“username”) == ‘admin’:
    raise serializers.ValidationError(‘不能创建admin用户’)
  return attrs
1.3 在 user/views.py 中添加视图函数

from user.serializers import UserInfoSerializer
class UserInfoViewSet(APIView):
# 查询用户信息
  def get(self, request, *args, **kwargs):
# 一对多、多对多查询都是一样的语法
obj = User.objects.all()
ser = UserInfoSerializer(instance=obj,many=True) # 关联数据多个
# ser = UserInfoSerializer(instance=obj[0]) # 关联数据一个
return Response(ser.data, status=200)

创建用户

‘’‘创建用户’’’
def post(self,request):
ser = UserInfoSerializer(data=request.data)
# 判断提交数据是否合法
if ser.is_valid():
ser.save()
  
   return Response(data=ser.data, status=201)
   return Response(data=ser.errors,status=400)
  
  def put(self, request):
    pk = request.query_params.get(‘pk’)
    try:
      userinfo = User.objects.get(id = pk)
    except Exception as e:
      return Response(data=‘用户不存在’, status=201)
    # 创建序列化对象,并将要反序列化的数据传递给data构造参数,进而进行验证
    ser = UserInfoSerializer(userinfo,data=request.data)
    if ser.is_valid():
      ser.save()
      return Response(data=ser.data, status=201)
return Response(data=ser.errors,status=400)

写法:
from snippets.models import Snippet
from snippets.serializers import SnippetSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class SnippetList(APIView):
“”"
List all snippets, or create a new snippet.
“”"
def get(self, request, format=None):
snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data)

def post(self, request, format=None):
    serializer = SnippetSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

‘’‘根据ok值 进行查询编号,删除,修改’’’

class SnippetDetail(APIView):
“”"
Retrieve, update or delete a snippet instance.
“”"
‘’‘定义pk值.被调用’’’
def get_object(self, pk):
try:
return Snippet.objects.get(pk=pk)
except Snippet.DoesNotExist:
raise Http404

def get(self, request, pk, format=None):
    snippet = self.get_object(pk)
    serializer = SnippetSerializer(snippet)
    return Response(serializer.data)

def put(self, request, pk, format=None):
    snippet = self.get_object(pk)
    serializer = SnippetSerializer(snippet, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def delete(self, request, pk, format=None):
    snippet = self.get_object(pk)
    snippet.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)    

第二种方法路由写法

from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views

urlpatterns = [
path(‘snippets/’, views.SnippetList.as_view()),
path(‘snippets/int:pk/’, views.SnippetDetail.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

 类似资料: