标签:包括 put 技术分享 title 不用 一个 imp 写入 migration
定义序列化器(本质就是一个类),一般包括模型类的字段,有自己的字段类型规则。实现了序列化器后,就可以创建序列化对象以及查询集进行序列化操作,通过序列化对象.data来获取数据(不用自己构造字典,再返回Json数据)
废话不多说,直接上代码!!!
DRF序列化可以理解这几句
- 导入模块:from rest_framework import serializers - 建立一个序列化类 class BookSerializer(serializers.Serializer): 字段可以自定义 - 获取客户端请求数据 - 开始序列化 serialized_data = BookSerializer(origin_data, many=True) - 写入数据库 - 获取序列化后的数据,返回给客户端 return Response(serialized_data.data)
1.接口设计:
GET 127.0.0.1:8000/books/ # 获取所有数据,返回值: [{}, {}] GET 127.0.0.1:8000/books/{id} # 获取一条数据,返回值:{} POST 127.0.0.1:8000/books/ # 新增一条数据,返回值:{} PUT 127.0.0.1:8000/books/{id} # 修改数据,返回值:{} DELETE 127.0.0.1:8000/books/{id} # 删除数据,返回空
2.创建新的项目
models.py #表 class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() def __str__(self): return self.name class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) # 外键字段 publish = models.ForeignKey(to="Publish", related_name="book", related_query_name="book_query", on_delete=models.CASCADE) # 多对多字段 authors = models.ManyToManyField(to="Author")
3进行数据的迁移执行命令
python manage.py makemigrations
python manage.py migrate
4.开始创建视图和路由
urls.py from django.contrib import admin from django.urls import path from app1 import views urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘books/‘,views.BookView.as_view()), ]
views.py
from rest_framwork.views import APIView
from rest_framwork import serializers
from rest_fromwork.response import Response
class BookView(APIView): def get(self,request): book_list = Book.objects.all() # print(book_list) #进行数据的序列化 serializer_book_list = BookSerializer(book_list,many=True) #返回的时候必须带着data,因为所有的数据都在data里 return Response(serializer_book_list.data) def post(self,request): pass
5.创建序列化的类
urls.py calss BookSerializer(serializers,Serializer): title = serializers.CharField(max_length=32) price = serializers.DecimalField(max_digits=5,decimal_places=2) publish = serializers.CharField(max_length=32) author= serializers.CharField(max_length=32)
6.注意,现在的页面是这样的
7.改进的办法,也就是说我们序列化的重头戏‘
url.py class BookSerializer(serializers.Serializer): title = serializers.CharField(max_length=32) price = serializers.DecimalField(max_digits=5,decimal_places=2) publish = serializers.CharField(max_length=32) #这里必须是用SerializerMethodField()!!! authors_list = serializers.SerializerMethodField() #方法里有一个get_方法,注意!!!authors_list必须和上边的序列化一致否则报错找不到对应的方法! def get_authors_list(self,book_obj): author_list = list() for author in book_obj.authors.all(): author_list.append(author.name) return author_list
’
标签:包括 put 技术分享 title 不用 一个 imp 写入 migration
原文地址:https://www.cnblogs.com/lzqrkn/p/10079592.html