项目里的数据录入就不记录了,直接跳到序列化和视图函数的编写
1.序列化
假设我们有一个类如下,有若干属性
from datetime import datetime
class Comment(object):
def __init__(self, email, content, created=None):
self.email = email
self.content = content
self.created = created or datetime.now()
comment = Comment(email='test@example.com', content='foo bar')
最初步的序列化我们就用drf本身的serializer
from rest_framework import serializers
class CommentSerializer(serializers.Serializer):
email = serializers.EmailField()
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
这样,我们得出的序列化后的结果就是
serializer = CommentSerializer(comment)
serializer.data
# {'email': 'test@example.com', 'content': 'foo bar', 'created': '2020-05-10T12:07:10.375877'}
2.APIVIEW视图
上面的基础序列化讲完了以后,我们来看和本身模型结合的事情.
首先在我们goods这个app下面创建serializer.py
from rest_framework import serializers
class GoodsSerializer(serializers.Serializer):
name = serializers.CharField(required=True,max_length=100)
click_num = serializers.IntegerField(default=0)
goods_front_image = serializers.ImageField(default=0)
需要注意的是,要将基础序列化和Model结合使用,你在serializer里面的字段,必须要和Model的字段相匹配,不一定要全写上,但是serializer有的字段,必须Model里面要有,不然会报错
接着看views.py里面如何编写函数
from .serializer import GoodsSerializer
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Goods
# Create your views here.
class GoodsListView(APIView):
'''
List all
'''
def get(self,request,format=None):
goods = Goods.objects.all()[:10]
goods_serializer = GoodsSerializer(goods,many=True)
return Response(goods_serializer.data)
接着在urls.py里面设置路由
urlpatterns = [
path('xadmin/', xadmin.site.urls),
path('ueditor/',include('DjangoUeditor.urls')),
path('api-auth/',include('rest_framework.urls',namespace='rest_framework')),
#商品列表
path('goods/',GoodsListView.as_view(),name='goods-list'),]
这样我们就定义完了 127.0.0.1:8000/goods/
这个链接
我们来看一下访问后的效果
可以看到我们在serializer里面设置的字段,都显示出来了
3.ModelSerializer
上面是用基础serializer和模型进行匹配使用,那么是否有更加简单些的方法来使用呢?不用手动写这么多fields?
那就是ModelSerializer
class GoodsSerializer(serializers.ModelSerializer):
class Meta:
model = Goods
fields = ('name','click_num','market_price','add_time')
这个用法就是和ModelForm一样的,规定好fields,写好对应的model
并把Serializer改成ModelSerializer
如果你将fields设置为 'all'
那么他就可以把所有的fields都显示出来
不过可以看到category只显示了一个数字id,因为他是一个外键,那是否可以把这样的外键内容也显示出来呢?
那就需要再多创建一个CategorySerializer
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = GoodsCategory
fields = '__all__'
class GoodsSerializer(serializers.ModelSerializer):
category = CategorySerializer()
class Meta:
model = Goods
fields = '__all__'
这样,就可以把具体的category内容显示出来了