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


原文地址:https://www.cnblogs.com/SunshineKimi/p/13830297.html