zoukankan      html  css  js  c++  java
  • django restframework -模型序列化高级用法终极篇

    from django.db import models
    
    
    # 作者表
    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=15, 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")
    复制代码

    2.urls.py

    复制代码
    from django.urls import re_path
    from xfzapp import views
    
    urlpatterns = [
        re_path(r'books/$', views.BookView.as_view({
            'get': 'list',
            'post': 'create'
        })),
        re_path(r'books/(?P<pk>d+)/$', views.BookView.as_view({
            'get': 'retrieve',
            'put': 'update',
            'delete': 'destroy'
        }))
    ]
    复制代码

    3.views.py

    复制代码
    from rest_framework import generics
    from rest_framework.viewsets import ModelViewSet
    from .models import Book
    from .xfz_serializers import BookSerializer
    
    
    class BookFilterView(generics.RetrieveUpdateDestroyAPIView):
        queryset = Book.objects.all()
        serializer_class = BookSerializer
    
    
    class BookView(ModelViewSet):
        queryset = Book.objects.all()
        serializer_class = BookSerializer
    复制代码

    4.序列化类

    复制代码
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # 导入模块
    from rest_framework import serializers
    from .models import Book
    
    class BookSerializer(serializers.ModelSerializer):
        class Meta:
            model = Book
    
            fields = ('title',
                      'price',
                      'publish',
                      'authors',
                      '_author_list',
                      '_publish_name',
                      '_publish_city'
                      )
            extra_kwargs = {
                # 以下字段和fields里面的是同一个,加上只写,是不想让客户看见,因为它是一个数字
                'publish': {'write_only': True},
                'authors': {'write_only': True}
            }
        # 带有前缀"_"说明不是表中原有字段
        _publish_name = serializers.CharField(max_length=32, read_only=True, source='publish.name')
        _publish_city = serializers.CharField(max_length=32, read_only=True, source='publish.city')
    
        _author_list = serializers.SerializerMethodField()
        # "get_"是固定格式,"get_"后面部分与author_list保持一致,不能随便写
        def get__author_list(self, book_obj):
            # 拿到queryset开始循环 [{}, {}, {}, {}]
            authors = list()
            for author in book_obj.authors.all():
                authors.append(author.name)
            return authors


  • 相关阅读:
    二分查找(通过相对位置判断区间位置)--17--二分--LeetCode33搜索旋转排序数组
    归并排序(归并排序求逆序对数)--16--归并排序--Leetcode面试题51.数组中的逆序对
    22-Java-Hibernate框架(二)
    21-Java-Hibernate框架(一)
    操作系统-5-进程管理(二)
    操作系统-4-进程管理(一)
    操作系统-3-操作系统引论
    操作系统-2-存储管理之LRU页面置换算法(LeetCode146)
    20-Java-正则表达式
    19-Java-核心类库2-包装类、Integer类、String类、StringBuffer类、StringBuilder类
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/13830297.html
Copyright © 2011-2022 走看看