码迷,mamicode.com
首页 > 其他好文 > 详细

drf序列化组件

时间:2018-12-11 21:42:25      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:rgs   eth   birt   bsp   date   views   pre   books   重写属性   

models

from django.db import models


# Create your models here.

class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    publish_date = models.DateField()

    publish = models.ForeignKey(to=Publish, to_field=nid, on_delete=models.CASCADE)
    authors = models.ManyToManyField(to=Author)

    def __str__(self):
        return self.name


class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    author_detail = models.OneToOneField(to=AuthorDatail, to_field=nid, unique=True, on_delete=models.CASCADE)


class AuthorDatail(models.Model):
    nid = models.AutoField(primary_key=True)
    telephone = models.BigIntegerField()
    birthday = models.DateField()
    addr = models.CharField(max_length=64)


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

    def test(self):
        return self.email

views

from django.shortcuts import render
from django.http import JsonResponse
# Create your views here.
from rest_framework.views import APIView
from app01 import models
from app01.myser import BookSerializer


class Books(APIView):
    def get(self, request, *args, **kwargs):
        book = models.Book.objects.all()
        book_ser = BookSerializer(book, many=True)
        print(book_ser.data)
        return JsonResponse(book_ser.data, safe=False)

myser

from rest_framework import serializers


class AuthorSerializer(serializers.Serializer):
    name = serializers.CharField()
    age = serializers.CharField()
    telephone = serializers.CharField(source=author_detail.telephone)
    

# class BookSerializer(serializers.Serializer):
#     # 可以用source修改别名,如果不指定source,字段必须对应起来,如果指定了source,字段可以任意命名
#     xx = serializers.CharField(source=‘name‘)
#     price = serializers.CharField()
#     sb = serializers.CharField(source=‘publish.city‘)
#source 可以指定字段,也可也指定方法,publish.test这是个方法,会执行该方法,并拿到返回结果
#     test = serializers.CharField(source=‘publish.test‘)
#     publish_id = serializers.CharField()

#     # SerializerMethodField,可以指定一个方法
#     # publish=serializers.SerializerMethodField()
#     # # 方法名:叫get_字段名,要传参数,参数是:当前book对象
#     # def get_publish(self,obj):
#     #     # obj 是当前book对象0
#     #     dic={‘name‘:obj.publish.name,‘email‘:obj.publish.email}
#     #     return dic

#     authors=serializers.SerializerMethodField()
#     # def get_authors(self,book):
#     #     #拿到这本书的所有作者
#     #     aus=book.authors.all()
#     #     # 拼出一个列表,列表中套字典,每个字典是一个作者
#     #     ll=[]
#     #     for a in aus:
#     #         ll.append({‘name‘:a.name,‘age‘:a.age})
#     #     return ll
#     def get_authors(self,book):
#         #拿到这本书的所有作者
#         aus=book.authors.all()
#         # 可以继续用序列化类,来处理
#         auth_ser=AuthorSerializer(aus,many=True)
#         return auth_ser.data
from ap01.models import Book


# class BookSerializer(serializers.ModelSerializer):
#     # 必须写一个内部类,名字叫Meta
#     class Meta:
#         model = Book
#         fields = ‘__all__‘
#     # 重写属性
#     publish = serializers.CharField(source=‘publish.name‘)
#     authors = serializers.SerializerMethodField()
#     def get_authors(self, book):
#         # 拿到这本书的所有作者
#         aus = book.authors.all()
#         # 可以继续用序列化类,来处理
#         auth_ser = AuthorSerializer(aus, many=True)
#         return auth_ser.data


class BookSerializer(serializers.ModelSerializer):
    # 必须写一个内部类,名字叫Meta
    class Meta:
        model = Book
        # fields = ‘__all__‘
        # 指定只取这两个字段
        fields = [nid,name]
        # 去掉指定的字段
        # exclude=[‘publish‘,‘authors‘]
        # fields,跟exclude不能连用
        # 指定深度(官方建议小于10,我给你的建议小于3)
        # depth = 2

 

drf序列化组件

标签:rgs   eth   birt   bsp   date   views   pre   books   重写属性   

原文地址:https://www.cnblogs.com/liweiwei0307/p/10105102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!