程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Rewrite get method and source code analysis using djangorestframework serializer

編輯:Python

Rewrite the query interface

Create a new sub application

python manage.py startapp book_drf, Apply this child to the parent application setting.py Register in , Then the parent application urls.py New routes for , The route assigned to the sub application , In sub application urls.py Add route to , Point to the view in the sub application views.py Class name in .

from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url('projects/', include('testdjango.urls')),
url('projects/', include('book_drf.urls')),
]
from django.urls import path
from django.conf.urls import url
from book_drf import views
urlpatterns = [
url(r'^book_drf/$', views.Books.as_view()),
url(r'^book_drf/(?P<pk>\d+)/$', views.Book.as_view()),
]

In the view of the new sub application (views) First import and use django The view of

You need to create a serializer ,serializer.py, Write as many fields as you need to return , The type of the field is the same as models The same type in

from rest_framework import serializers
# Custom serializer , The essence is a class
class BookSerializer(serializers.Serializer):
# Serialize the returned fields
btitle = serializers.CharField()
bpub_date = serializers.DateField()
bcomment = serializers.IntegerField()

stay view.py Rewriting in get Method , Convert object data to json data , Use serializers directly , When multiple objects return, you need to add many=True. After serialization, it is also an object , In this object data Is the serialized content . There is no need to return a single object many=True

from django.shortcuts import render
from django.views import View
from testdjango.models import BookInfo
from book_drf.serializer import BookSerializer
from django.http import JsonResponse
class Books(View):
def get(self, request):
books = BookInfo.objects.all()
# When multiple objects return, you need to add many=True
ser = BookSerializer(books, many=True)
return JsonResponse(ser.data, safe=False)
class Book(View):
def get(self, request, pk):
book = BookInfo.objects.get(id=pk)
ser = BookSerializer(book)
return JsonResponse(ser.data)

http://127.0.0.1:8000/projects/book_drf/

 http://127.0.0.1:8000/projects/book_drf/1/

  Use of serializer , It can be seen that , This serializer class has a data Method , however BookSerializer This is not defined in data Method . But it inherited serializers.Serializer.

 ser = BookSerializer(books)
return JsonResponse(ser.data)

spot Serializer View source code , Find out if there is a data() Method

  You can see this data Method is to return a dictionary type data , But the class name does not use parentheses when calling this method ,ser.data. It's because of this data There is a method on it @property Decorator , Use methods as attributes . All can use the class name directly +“.”  In the form of .

You can see that this method actually has a parent class that uses it data(), Go in and have a look , There's a self.instance This attribute is the object that receives the message

  When we use serialization, we pass an object data to the serializer ,

 ser = BookSerializer(books)

  In this parent class BaseSerializer The initialization method can be found , Make a breakpoint to verify .instance After receiving the object , Assign a value to self.instance, This can be used in the whole class instance attribute

  Then come back to see data() Method ,data Method to judge self.instance Is it empty , After not empty , call self.to_representation This method . hold self.instance Value , That is, object data , Pass in as an input parameter


if not hasattr(self, '_data'):
if self.instance is not None and not getattr(self, '_errors', None):
self._data = self.to_representation(self.instance)
elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None):
self._data = self.to_representation(self.validated_data)
else:
self._data = self.get_initial()
return self._data

Click in self.to_representation Take a look at this method , It depends on whether this method is required

To sum up, our data objects are Parent class BaseSerializer Medium instance Property received . And when you use it

ser.data When , This data It's not a property , It's actually a way , Just use the @property Decorator , Use it as an attribute .data The method is to extract data objects and convert them into dictionaries , Convert to json Formatted data .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved