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



浙公网安备 33010602011771号