Django Rest Framework serial interfaces (GET and POST) design (early version)!

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)

 

Create a django project;

Create an app, and named: books

 

 1 INSTALLED_APPS = [
 2     'django.contrib.admin',
 3     'django.contrib.auth',
 4     'django.contrib.contenttypes',
 5     'django.contrib.sessions',
 6     'django.contrib.messages',
 7     'django.contrib.staticfiles',
 8     'books',
 9     'rest_framework'
10 ]
settings.py
from django.contrib import admin
from django.urls import path
from books import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('book/',views.BookView.as_view())
]
urls.py
from django.shortcuts Import the render, the HttpResponse
 from . Import Models 

# 1. django native sequence of assembly for use 
from django.views Import View
 from django.core.serializers Import the serialize
 # 1.Django use of the native sequence 
# class BookView (View) : 
#      DEF GET (Self, Request): 
#          # Get queryset 
#          book_list Book.objects.all = () 
#          # to serialize queryset 
#          serialize_data the serialize = ( 'JSON', book_list) 
#          data return sequence of the #
#          Return the HttpResponse (serialize_data) 


# 2.1-sequence of the DRF assembly for use 
from rest_framework.views Import APIView
 from rest_framework.response Import the Response
 # Create a file in the application: serizlizer.py related needs to write the serialized data 
# Import serizlizer. py in the file: BookSerizlizer class 
from .serizlizer Import BookSerizlizer 


class BookView (APIView):
     DEF GET (Self, Request):
         # get the book object data 
        book_obj = models.Book.objects.all ()
         # create a serializer , passing the book object data.
        = BookSerizlizer serialized_data (book_obj, MANY = True)
         # return data serialized DRF. A final point data in order to get results 
        return the Response (serialized_data.data) 

    # access 127.0.0.1:8000/books / ==> The following is the page get data (authors field is not normal, 
    # as the book authors in the database table is many to many fields, 
    # so def a method to get the data which serizlizer.py) 
    '' '     [ 
    { 
        "NID": " . 1 ", 
        " title ":" Python primary ", 
        ". price ":" 188.00 ", 
        " publish ":" University Press ", 
        " the authors ":" serializer.Author.None " 
    }, 
    { 
        " NID ":" 2",
        "title": "python Intermediate", 
        "price": "78.00",
        "publish": "Tsinghua University Press" 
        "the authors": "serializer.Author.None" 
    },    
          ] 
    '' ' 

    DEF post (Self, Request):
         ' '' for post serialization component interfaces (data submitted to an ) design, the following steps: 
    - definition of the post method: post method defined in the view class; 
    - starting sequence of: the sequence of categories defined above, to create a serialized object, arguments passed data = request.data (application / json ) transactions; 
    - verification data: method of validity of the request data is checked by is_valid object instance (); 
    - save data: calling save () method, the data into the database; 
    - inserting data into many relationship table: If there is a field-many, many-to manually insert the data into relational tables; 
    - returns: returns the inserted object; 
      '' ' 
        serialized_data = BookSerizlizer (data = request.data)
         IF serialized_data.is_valid ():
            book =serialized_data.save ()
             # manually bind many relationships, the method may also be placed to create 
            the authors = models.Author.objects.filter (nid__in request.data = [ ' the authors ' ]) 
            book.authors.add ( * the authors)
             return the Response (serialized_data.data)
         the else :
             return the Response (serialized_data.errors) 

'' ' analysis: this method has the above two problems: one is the need to manually insert the data (write the write sequence classes create methods), 
the other If the field is a lot, write serialization class field will become a burden, then there is no simpler way? Of course, 
that is to use ModelSerializer! So we need to modify the code in the serializer.py '' '
views.py
from django.db import models

# Create your models here.

class Book(models.Model):
    nid = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    publish = models.ForeignKey(to='Publish', related_name='book', on_delete=models.CASCADE)
    authors = models.ManyToManyField(to='Author')


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 Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()

    def __str__(self):
        return self.name
mdoels.py
# . 2.1-introduced sequence module to create a serialized data class 
from rest_framework Import serializers 

# a version of the class sequence 
# class BookSerizlizer (serializers.Serializer): 
#      NID = serializers.CharField (MAX_LENGTH = 32) 
#      title = serializers .CharField (MAX_LENGTH = 128) 
#      . price serializers.IntegerField = () 
#      publish = serializers.CharField (MAX_LENGTH = 32) 
#      # = serializers.CharField the authors (MAX_LENGTH = 32) as a many-#authors fields, you should use the following method 
#      in the authors serializers.SerializerMethodField = () 
# 
#      # define a method to get many to many field data, attention: get_ field must be consistent with the field names, otherwise an error. And pass a book Object 
#     get_authors DEF (Self, book_obj): 
#          in the authors = [] 
#          # book_obj.authors.all () to get the corresponding author of each book (for example:. models.Book.objects.first () authors.all () to get the first author of the book) 
#          for author in book_obj.authors.all (): 
#              # add the author's name into it, (author.name) 
#              authors.append (author.name) 
#          return in the authors 

# on POST interface requires re-write about BookSerizlizer class 
' '' Note: because many relationship field is our custom, and must be so defined, the returned data makes sense, 
but when the user inserts the data, can not find the field type SerializerMethodField, 
therefore, serialization class can not help us insert data into many-to-table, we must manually insert data! ! ! The above sequence annotation class !!! So do the serialization class to do the following changes: '' ' 
# two versions serialization class 
# from .models Book Import
# 
# Class BookSerizlizer (serializers.Serializer): 
#      # NID field only to the client, the user need not submit id, so = True READ_ONLY 
#      NID = serializers.CharField (READ_ONLY = True, MAX_LENGTH = 32) 
#      title = serializers .CharField (MAX_LENGTH = 128) 
#      . price = serializers.DecimalField (max_digits =. 5, decimal_places = 2) 
#      publish = serializers.CharField (MAX_LENGTH = 32) 
#      # SerializerMethodField default = True READ_ONLY 
#      the authors serializers.SerializerMethodField = () 
# 
#          # define a method to get many to many field data, attention: get_ field must be consistent with the field names, otherwise an error. And pass a book Object 
#      DEF get_authors (Self, book_obj): 
#         = the authors [] 
#          # book_obj.authors.all () to get the corresponding of each book (for example:. models.Book.objects.first () authors.all () to get the first of the book) 
#          for in book_obj.authors.all author (): 
#              # add the author's name into it, (author.name) 
#              authors.append (author.name) 
#          return in the authors 
# 
#      # must manually insert data, the data must be submitted by post method there create method! 
#      DEF create (Self, validated_data): 
#          Print (validated_data) # validated_data data after filtering 
#          validated_data [ 'publish_id'] = validated_data.pop ( 'publish') 
#          Book Book.objects.create = ( validated_data **) 
# 
#         Book return 

# three class version sequence 
from . Import Models
 # use ModelSerializer, post method is no longer dependent on the method create 
class BookSerizlizer (serializers.ModelSerializer):
     class Meta -: 
        Model = models.Book 
        Fields = (
             ' title ' ,
             ' . price ' ,
             ' publish ' ,
             ' the authors ' ,
             ' author_list ' ,
             'pubName',
            'pubCity'
        )
        extra_kwargs = {
            'publish':{'write_only':True},
            'authors':{'write_only':True}
        }

    pubName = serializers.CharField(max_length=32, read_only=True, source='publish.name')
    pubCity = serializers.CharField(max_length=32, read_only=True, source='publish.city')

    # 多对多字段
    author_list = serializers.SerializerMethodField()

    def get_author_list(self, book_obj):
        authors = list()

        for author in book_obj.authors.all():
            authors.append(author.name)

        return authors
serizlizer.py

 

Guess you like

Origin www.cnblogs.com/cou1d/p/12333340.html