DRF (Django Rest Framework) interface and the serialization interface design components -! GET Interface Design!

Defined serializer (essentially a class), generally includes a model class field, field type has its own rules. After the realization of the serializer, you can create a sequence of objects and sets the query sequence operation, .data to obtain the data through serialized objects (do not have to construct the dictionary, then return Json data)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'apps.apps.AppsConfig',
    'app01',
    'rest_framework', #把drf组件注册进去
]
Project home directory /settings.py

 

from django.db import models

# Create your models here.
class Book(models.Model):
    nid = models.IntegerField(primary_key=True)
    title = models.CharField(max_length=32)
    #第三张表
    author = models.ManyToManyField(to='Author')
class Publish(models.Model):
    nid = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=32)
    address = models.CharField(max_length=32)
    email = models.EmailField(max_length=128)

class Author(models.Model):
    nid  = models.IntegerField(primary_key=True)
    name =models.CharField(max_length=32)
    age = models.IntegerField()
app01/models.py
from django.shortcuts import render
from django.db import models
from .models import Book
from .models import Publish
from .models import Author

# Create your views here.
from apps.models import Course
from django.core.serializers import serialize
from rest_framework.views import APIView
from rest_framework import serializers
fromrest_framework.response Import the Response 

# Create a sequence of class 
class BookSerizlizer (serializers.Serializer): 
    NID = serializers.CharField (MAX_LENGTH = 10 ) 
    title = serializers.CharField (MAX_LENGTH = 32 )
     # added to the associated data of the book pool 
    = author serializers.SerializerMethodField ()
     # create a method must: get_ field names, and pass an object. 
    DEF get_author (Self, book_obj): 
        author_list = List ()
         for A in book_obj.author.all (): 
            author_list.append ({ ' name ': a.name, ' Age ' : STR (a.age)}) 

        return author_list 



class Courses (APIView):
     DEF GET (Self, Request): 
        old_data = Book.objects.all ()
         # Start json serialized data 
        new_data = BookSerizlizer (old_data, MANY = True)
         Print (the response)
         # data after the sequence of the response to the client 
        return the response (new_data.data) 

    DEF POST (Self, Request):
         Pass

 

 

      

 

 

             

 

 

Guess you like

Origin www.cnblogs.com/cou1d/p/12322997.html
Recommended