ModelSerializer模型类序列化器
class BookSerializer2(serializers.ModelSerializer): class Meta: model = Book # 跟那个表有关系 # fields='__all__' # 所有字段 # id是从表模型中映射过来的,auto,它会不要求你传 # price_info:它不是数据库中字段 # 即便扩写的字段,也要在fields中注册 fields = ['id', 'name', 'price', 'author', 'price_info'] # 原来的字段参数,通过extra_kwargs传进去 extra_kwargs = { 'name': {'write_only': True, 'max_length': 8, 'min_length': 3} }
class BookSerializer2(serializers.ModelSerializer): class Meta: # 原来的字段参数,通过extra_kwargs传进去 extra_kwargs = { 'name': {'write_only': True, 'max_length': 8, 'min_length': 3} }
序列化多表操作
models.py
from django.db import models # Create your models here. class Book(models.Model): name = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE) authors = models.ManyToManyField(to='Author') def __str__(self): return self.name @property def publish_detail(self): return {'name': self.publish.name, 'city': self.publish.city} @property def author_list(self): l = [] for author in self.authors.all(): l.append({'name': author.name, 'age': author.age, 'addr': author.author_datail.addr}) return l class Author(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() author_datail = models.OneToOneField(to='AuthorDatail', on_delete=models.CASCADE) class AuthorDatail(models.Model): telephone = models.BigIntegerField() addr = models.CharField(max_length=64) class Publish(models.Model): name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField()
views.py
from rest_framework.views import APIView from rest_framework.response import Response from .models import * from .serializer import * class BookView(APIView): def get(self, request): book_list = Book.objects.all() ser = BookSerializers(instance=book_list, many=True) return Response(ser.data) def post(self, request): ser = BookSerializers(data=request.data) if ser.is_valid(): ser.save() return Response({"code": 100, "msg": "新增成功", "data": ser.data}) return Response({"code": 101, "msg": "新增出错", "err": ser.errors}) class BookDataView(APIView): def get(self, request, pk): book = Book.objects.all().filter(pk=pk).frist() ser = BookSerializers(instance=book) return Response(ser.data) def put(self, request, pk): book = Book.objects.all().filter(pk=pk).first() ser = BookSerializers(instance=book, data=request.data) if ser.is_valid(): ser.save() return Response({"code": 100, "msg": "修改成功", "data": ser.data}) return Response({"code": 101, "msg": "修改出错", "err": ser.errors}) def delete(self, request, pk): Book.objects.filter(pk=pk).delete() return Response({"code": 100, "msg": "删除成功", })
serializer.py
from .models import * from rest_framework import serializers class BookSerializers(serializers.ModelSerializer): class Meta: model = Book fields = ['id', 'name', 'price', 'authors', 'publish', 'publish_detail', 'author_list'] extra_kwargs = { 'publish': {'write_only': True}, 'authors': {'write_only': True} } class AuthorSerializers(serializers.ModelSerializer): class Meta: model = Author fields = '__all__' class AuthorDatailSerializers(serializers.ModelSerializer): class Meta: model = AuthorDatail fields = '__all__' class PublishSerializers(serializers.ModelSerializer): class Meta: model = Publish fields = '__all__'