VARIS VONGUEA-AREE

PHP 🐍 Python 🔥 Golang 🇹🇭 Bangkok Thailand

High level experience in web design and development knowledge, producing quality work.

For more info
  • Home
  • About
  • Project
  • Blog
  • Varisz
  • Python
  • Django Rest Framework

Django Rest Framework

$ curl http://localhost:8000/api/article/?format=json

ส่วนสำคัญสำหรับ Django Rest Framework มี 3 ส่วนหลัก

Models

Serializers

class PollSerializer(serializers.ModelSerializer):
      choices = ChoiceSerializer(many=True, read_only=True,
required=False)
      class Meta:
          model = Poll
          fields = '__all__'

A is_valid(self, ..) method which can tell if the data is sufficient and
valid to create/update a model instance.
A save(self, ..) method, which khows how to create or update an
instance.
A create(self, validated_data, ..) method which knows how to
create an instance. This method can be overriden to customize the create
behaviour.
A update(self, instance, validated_data, ..) method which knows
how to update an instance. This method can be overriden to customize the
update behaviour.

Viewsets

ModelViewSet, which provides the following actions: .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy() .

from rest_framework import viewsets, filters
from .models import Website
from .serializers import WebsiteSerializerclass WebsiteViewSet(viewsets.ModelViewSet):
     queryset = Website.objects.all()
     serializer_class = WebsiteSerializer

ติดตั้ง Django Rest Framework

pip install djangorestframework
pip install django-filter

เพิ่ม rest_framework เข้าไปใน INSTALLED_APPS ในไฟล์ settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
]

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
}

เพิ่ม path api เข้าไปในไฟล์ urls.py

from .routers import router

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include(router.urls)),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

สร้างไฟล์ routers.py

from rest_framework import routers

router = routers.DefaultRouter()

© 2021 All rights reserved by varisz