DRF序列化代码
DRF序列化
--- 要安装Djangorestframework
--- 要使用的时候要在setting中注册app--rest_framework
--- 使用之前要定义一个序列化器,指定要序列化的字段
下面 是models中的表:
from django.db import models # Create your models here. __all__ = ['Book','Publisher','Auth'] class Book(models.Model): title = models.CharField(max_length=32) CHOICES = ((1,'python'),(2,'linux'),(3,'go')) category = models.IntegerField(choices=CHOICES,max_length=32) publisher = models.ForeignKey(to='Publisher') auth = models.ManyToManyField(to='Auth') # def __str__(self): # return self.title class Publisher(models.Model): name = models.CharField(max_length=32) def __str__(self): return self.name class Auth(models.Model): name = models.CharField(max_length=32) def __str__(self): return self.name
---新建一个py文件当做序列化器
from rest_framework import serializers class PublisherSerializers(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField(max_length=32) class AuthSerializers(serializers.Serializer): id = serializers.IntegerField() name = serializers.CharField(max_length=32) class BookSerializers(serializers.Serializer): id = serializers.IntegerField() title = serializers.CharField(max_length=32) category = serializers.CharField(source='get_category_display') publisher = PublisherSerializers() auth = AuthSerializers(many=True)
manytomany,多对多的外键关系,要指定many=True,这样序列化的时候就会循环序列化每一个对象
category = serializers.CharField(source='get_category_display')
当有choices字段的时候可以使用source关键字来指定后面 执行的操作,可以跟ORM 操作
---在view文件中使用:
class Book(APIView): def get(self,request): book_query = models.Book.objects.all() print(book_query) book_ser = myserializers.BookSerializers(book_query,many=True) return Response(book_ser.data)