1. 程式人生 > >【DRF】CRUD 之 R(Read) - (例項場景:我的部落格專欄=> 設計模式打造超級蜘蛛)

【DRF】CRUD 之 R(Read) - (例項場景:我的部落格專欄=> 設計模式打造超級蜘蛛)

CRUD of Django-REST-Framework 之 R(Read)

Overview

1. 例項 django ORM model 回顧

class Site(models.Model):
    site = models.CharField(max_length=200)
    category = models.CharField(max_length=64)
    start_date =
models.DateTimeField(auto_now=True) def __str__(self): return self.site

關於 Django ORM => model 中的 __str__ 特殊方法:
n/a
(note: 需要其支援 str() 否則需自己實現;正例: CharField; 反例: DatetimeField, ForeignKey)

2. Coding to support Read

a) 這是第一次使用 REST Framework,所以需要 Serialize

i. 什麼是 Serialize

N/A

ii. 建立 serialize.py

N/A

b) ORM model mapping 的 Serialize

class SiteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Site
        fields = '__all__'

關於特殊方法 __all__:
N/A

c) urls.py

API 設計(或者說結構)
http://domain:port/api/sites/ - read sites list
http://domain:port/api/sites/<pk>/ - read one specific site

#### <django-proj>/api/urls.py
from django.urls import path
from django.http import HttpResponse

#
# API View
#
from .views import SiteList
from .views import SiteDetail


urlpatterns = [
    # 'http://domain:port/api/' \/
    path("", lambda request: HttpResponse("<h1>Hello Django REST Framework API</h1>")),

    path("sites/", SiteList.as_view(), name='sites_list'),
    path("sites/<int:pk>/", SiteDetail.as_view(), name="sites_detail"),
]

d) views.py

from django.shortcuts import render

# Create your views here.
from django.shortcuts import Http404, get_object_or_404

#####################################
# generic views
#####################################
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response

from api.models import Site
from .serializers import SiteSerializer


class SiteList(APIView):
    queryset = Site.objects.all()

    def get(self, request):
        sites = Site.objects.all()
        data = SiteSerializer(sites, many=True).data
        return Response(data)


class SiteDetail(APIView):
    queryset = Site.objects.all()

    def get(self, request, pk):
        site = get_object_or_404(Site, pk=pk)
        data = SiteSerializer(site).data
        return Response(data)

3. Test

a) create one by manual

(Note: 在 admin 後臺管理中建立,model 註冊 admin 用索引其它 blog 內容)

(建立內容 here)

b) GET(Read) It - n/a

  1. browser

  2. postman


Reference