DRF框架的serializers使用简介

django版本3.1.5 安装DRF

pip3 install djangorestframework==3.11.2

 

表设计

from django.db import models

# Create your models here.


class Category(models.Model):
    """
    文章分类
    """
    name = models.CharField(verbose_name='分类', max_length=32)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "文章分类"
        verbose_name_plural = verbose_name


class Article(models.Model):
    """
    文章表
    """
    title = models.CharField(verbose_name='标题', max_length=32)
    summary = models.CharField(verbose_name='简介', max_length=255)
    content = models.TextField(verbose_name='文章内容')
    category = models.ForeignKey(Category, on_delete=models.CASCADE, default="")

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = "文章表"
        verbose_name_plural = verbose_name

 

在app同目录的admin.py中注册数据表

admin.py

from django.contrib import admin

# Register your models here.


from drf_app import models

admin.site.register(models.Category)
admin.site.register(models.Article)

 

注册APP 注册drf_app,在settings中INSTALLED_APPS注册drr_app:

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'drf_app.apps.DrfAppConfig',
    'rest_framework',
]

 

写路由

urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from django.urls import re_path
from drf_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    # 文章类型路由
    path('drf/category/', views.NewCategoryView.as_view()),
    re_path('^drf/category/(?P\d+)/$', views.NewCategoryView.as_view()),
    # 文章路由
    path('drf/article/', views.NewArticleView.as_view()),
    re_path('^drf/article/(?P\d+)/$', views.NewArticleView.as_view()),
]

 

 

视图函数

views.py

from drf_app import models
from rest_framework.response import Response
from rest_framework.views import APIView
from drf_app.serializer import *


class NewArticleView(APIView):
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')    # 获取单条数据的pk值
        if not pk:
            queryset = models.Article.objects.all()
            ser = ArticleSerializer(instance=queryset, many=True)
            return Response(ser.data)   # Response 只接受列表,字典,字符串类型的数据
        else:
            if models.Article.objects.filter(pk=pk):
                obj_dict = models.Article.objects.filter(pk=pk).first()
                ser = ArticleSerializer(instance=obj_dict, many=False)
                return Response(ser.data)
            else:
                return Response({"code": "500", "msg": "记录不存在"})

 

 serializers模块:显示关联表的数据值

serializer.py

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Category
        fields = "__all__"

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Article
        fields = ['id', 'title', 'summary', 'content', 'category']

 

准备数据

启动程dong

python manage.py runserver 8000

 

页面请求接口

GET /drf/article/12/

HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": 12,
    "title": "serializer",
    "summary": "序列化简介",
    "content": "序列化测试",
    "category": 4
}
 
serializer.py 中的 ArticleSerializer 类没有跟 CategorySerializer 有关联,直接将 Article 表的 category 字段的数据返回

 

ArticleSerializer 类添加 depth 字段,返回外键所有的字段

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Article
        fields = ['id', 'title', 'summary', 'content', 'category']
     depth = 1   # 返回外键所有的字段
 
GET /drf/article/12/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": 12,
    "title": "serializer",
    "summary": "序列化简介",
    "content": "序列化测试",
    "category": {
        "id": 4,
        "name": "英语"
    }
}

这里的depth字段,是将Article 里的所有外键对应表的字段都获取过来

 

如果想要能够更加个性化的获取外键关联表的字段数据,可以对外键进行实例化  CategorySerializer()

class ArticleSerializer(serializers.ModelSerializer):
    category = CategorySerializer()  # 返回字段根据 CategorySerializer 变化

    class Meta:
        model = models.Article
        fields = ['id', 'title', 'summary', 'content', 'category']

GET /drf/article/12/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": 12,
    "title": "serializer",
    "summary": "序列化简介",
    "content": "序列化测试",
    "category": {
        "id": 4,
        "name": "英语"
    }
}


此时针对CategorySerializer 进行一些修改

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Category
        fields = ['name']
 再次调接口
 
 
GET /drf/article/12/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": 12,
    "title": "serializer",
    "summary": "序列化简介",
    "content": "序列化测试",
    "category": {
        "name": "英语"
    }
}
 
CategorySerializer 类只返回 name 字段,ArticleSerializer 的 category 也只有 name字段

 

参考文档

1、https://www.cnblogs.com/welan/p/10151714.html 

posted @ 2021-01-25 22:33  DeyouKong  阅读(186)  评论(0编辑  收藏  举报