DRF use to quickly implement an API call service

This post last edited by the Fan Zhiyuan at 2019-3-19 16:55

increase load options Djagno REST Framework module
for INSTALLED_APPS settings.py file increases 'rest_framework' add-ons. To use this framework to generate REST API calls service, you need to achieve the following three modules:
the Serializer: deciding how to serialize (or deserialize) model entities
ViewSet: decide which model to serialize entity
URL pattern: deciding how to resolve a URL for the corresponding services
amount of code required seems to achieve the most basic services API and a lot of ah, but after this module division, the fact became clear framework program a lot, and have a more robust scalability.
Serializer achieve
a new file blog / serializer.py, as follows:
# Coding: UTF-. 8
from rest_framework Import serializers
from the User .models Import, the Entry

class UserSerializer (serializers.ModelSerializer):
    class Meta -:
        Model = the User
        Fields = ( 'name ',' mail ')

class EntrySerializer (serializers.ModelSerializer):
    class Meta -:
        Model = the Entry
        Fields = ( 'title', 'body', 'the created_at', 'Status', 'author')

above is the definition of a Serializer most simple code, model specified model entity corresponding, fields specify the sequence of the data field (regarded as a column of a database table).

  
It is worth mentioning that the EntrySerializer the author, as a foreign key, default output corresponding model entity (the User) a sequence of results. Of course, we can modify the sequence of implementation.



ViewSet achieve
a new file blog / views.py, as follows:

# Coding: UTF. 8-
Import django_filters
from rest_framework Import viewsets, Filters
from the User .models Import, the Entry
from .serializer Import UserSerializer, EntrySerializer

class UserViewSet (viewsets.ModelViewSet):
    = User.objects.all QuerySet ()
    serializer_class = UserSerializer

class EntryViewSet (viewsets.
    queryset = Entry.objects.all()
    serializer_class = EntrySerializer



实现URL pattern
修改django_rest_framework_test/urls.py,内容如下:

# coding: utf-8
from django.conf.urls import url, include
from django.contrib import admin
from blog.urls import router as blog_router

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # blog.urlsをincludeする
    url(r'^api/', include(blog_router.urls)),
]

新建一个文件blog/urls.py,内容如下:

# coding: utf-8
from rest_framework import routers
from .views import UserViewSet, EntryViewSet

router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register (r'entries', EntryViewSet)

this URL defined pattern is complete, / api / REST API is the entrance to our service
Article from: https: //blog.csdn.net/gg_18826075157/article/details/72869974

Guess you like

Origin www.cnblogs.com/abdm-989/p/12003492.html