一.models.py中
from django.db import models class UserModel(models.Model) user_name = models.CharField() class MyModel(models.Model) author = models.Foreignkey(user) age = models.CharField()
二. 序列化文件 serializers.py 中创建序列化类
from rest_framework.serializers import Serializer from models import MyModel class MySerializer( Serializer.ModelSerializers): # 自定义字段 user_name = serializers.SerializerMethodField() class Meta: model = MyModel fields = ("user_name", "age") # 处理自定义的字段返回用户名, 通过外键获取UserModel的数据 def get_user_name(self, obj): return obj.user.user_name def create(self, validated_data) # 处理外键字段 return MyModel.objects.create(author=self.context["author"], **validated_data)
三.视图文件views.py中定义视图
# 视图函数中 from rest_framework.views import APIView # 类视图中使用,集成自该类 from rest_framework.decorators import api_view # 方法视图中使用,是一个装饰器,直接装饰方法视图 from rest_framework import status from rest_framework.response import Response # 直接可以将字典数据转换成json数据 from models import MyModel from serializers import MySerializer from rest_framework.request import Request from rest_framework import exceptions @api_view([‘GET‘, ‘POST‘, ‘PUT‘, ‘DELETE‘]) # 指明允许那些请求方式进行请求 def api_list(request): if request.method == ‘GET‘: # 向数据库查询数据,得到查询集 try: query_set = MyModel.objects.all() except Snippet.DoesNotExist: return Response(status=status.HTTP_417_EXPECTATION_FAILED) # 调用序列化类对象,返回进行了序列化的字段集合,使用serializers.data方式 获取数据 serializers = MySerializer(query_set, many=True) # 取出数据,向客户端进行返回,Response()会将数据转化为json数据. return Response(serializers.data, status=status.HTTP_200_OK) # 前端提交数据,调用模型,将其保存到数据库中 elif request.method == ‘POST‘: user = request.user # 将外键数据插入 serializer = MySerializer(data= request.data, context={"author":user}) # 如果反序列化的对象存在,就说明数据有效,将数据保存到数据库中 if serializer.is_valid(): # 调用save(), 从而调用序列化对象的create()方法,创建一条数据 serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
原文地址:https://www.cnblogs.com/lowmanisbusy/p/9125454.html
时间: 2024-12-08 08:03:26