Để xây dựng một API RESTful đầy đủ chức năng trong Django, bạn cần kết hợp ba thành phần cốt lõi: ModelSerializer, ModelViewSet, và hệ thống định tuyến dựa trên DefaultRouter. Dưới đây là hướng dẫn thực hành rõ ràng, không phụ thuộc vào cấu trúc mẫu cứng nhắc, giúp bạn thiết lập toàn bộ luồng xử lý dữ liệu — từ ánh xạ mô hình sang JSON cho đến expose endpoint.
1. Tạo lớp Serializer tùy chỉnh
Thay vì sử dụng Serializer cơ bản, ta khai báo lớp kế thừa từ ModelSerializer để tự động suy diễn trường và quy tắc xác thực từ mô hình cơ sở dữ liệu.
# api/serializers.py
from rest_framework import serializers
from core.models import InventoryItem
class InventoryItemSchema(serializers.ModelSerializer):
item_code = serializers.CharField(read_only=True)
class Meta:
model = InventoryItem
fields = [
'id',
'item_code',
'name',
'quantity',
'unit_price',
'created_at'
]
read_only_fields = ['created_at']
2. Xây dựng ViewSet hỗ trợ CRUD đầy đủ
Lớp ModelViewSet cung cấp sẵn 5 hành động tiêu chuẩn (list, retrieve, create, update, destroy) mà không cần viết logic thủ công.
# api/views.py
from rest_framework import viewsets
from core.models import InventoryItem
from api.serializers import InventoryItemSchema
class InventoryItemEndpoint(viewsets.ModelViewSet):
queryset = InventoryItem.objects.select_related('category').all()
serializer_class = InventoryItemSchema
search_fields = ['name', 'item_code']
ordering_fields = ['created_at', 'quantity']
3. Đăng ký endpoint qua router động
Sử dụng DefaultRouter để tự động sinh các URL pattern tương ứng với từng phương thức HTTP — tránh việc khai báo thủ công từng path().
# api/urls.py
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from api.views import InventoryItemEndpoint
api_router = DefaultRouter()
api_router.register('items', InventoryItemEndpoint, basename='inventory')
urlpatterns = [
path('v1/', include(api_router.urls)),
]
4. Cấu hình toàn cục DRF (tối ưu hóa hiệu năng)
Các thiết lập trong settings.py ảnh hưởng trực tiếp đến hành vi mặc định của toàn bộ API — ví dụ như phân trang, kiểm soát quyền truy cập, hoặc định dạng phản hồi.
# settings.py
INSTALLED_APPS += ['rest_framework']
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 20,
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/day'
}
}
5. Khởi động và kiểm tra
Sau khi đảm bảo các tệp đã được import đúng trong urls.py chính và mô hình đã được migration, chạy lệnh sau để kích hoạt server phát triển:
python manage.py runserver 8001Khi truy cập http://localhost:8001/v1/items/, bạn sẽ thấy giao diện duyệt API tương tác, kèm theo khả năng gửi yêu cầu POST/PUT/DELETE ngay trong trình duyệt.
6. Cài đặt lại DRF nếu cần
Nếu gặp xung đột phiên bản hoặc lỗi import, hãy làm sạch và cài đặt lại bằng các lệnh sau:
pip uninstall djangorestframework -y<br>pip install --upgrade djangorestframeworkĐảm bảo kiểm tra phiên bản hiện tại bằng:
pip show djangorestframework