django-rest-framwork例子

rest_framwork Demo

下列代碼中分別使用了以下功能:python

  • serializers.HyperlinkedModelSerializer
  • viewsets.ModelViewSet
  • routers

代碼以下:django

settings.py

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "quickstart.apps.QuickstartConfig",
    "rest_framework"
]

models.py

from django.db import models


class TestGroup(models.Model):
    name = models.CharField(max_length=100, verbose_name="組名")
    desc = models.CharField(max_length=200, verbose_name="描述")
    role_id = models.IntegerField(default=1, verbose_name="1 主管 2組員")

    class Meta:
        db_table = "test_group"

    def __str__(self):
        return self.name

serialize.py

需本身新建api

from django.contrib.auth.models import User, Group
from quickstart.models import TestGroup
from rest_framework import serializers


class TestGroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = TestGroup
        fields = ("name", "desc", "role_id")


class UserSerializer(serializers.HyperlinkedModelSerializer):
    def create(self, validated_data):
        pass

    def update(self, instance, validated_data):
        pass

    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

views.py

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

from quickstart.models import TestGroup
from quickstart.serialize import UserSerializer, GroupSerializer, TestGroupSerializer


# Create your views here.

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


class GroupViewSet(viewsets.ModelViewSet):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


class TestGroupViewSet(viewsets.ModelViewSet):
    queryset = TestGroup.objects.all()
    serializer_class = TestGroupSerializer

    def get_queryset(self):
        """自定義get請求"""
        role_id = self.request.query_params.get("role_id", None)
        if role_id is None:
            queryset = super(TestGroupViewSet, self).get_queryset()
        else:
            queryset = TestGroup.objects.filter(role_id)
        return queryset

    @action(methods=["GET"], detail=True)
    def get_user(self, request, pk):
        """
        獲取主管方法:雖然request和pk在這裏沒使用,但也必需要傳
        將生成如下路由:
        網址格式(url_path): test_group/1/director/
        網址名稱(url_name): 'test_group-director'
        :param request:request
        :param pk:id
        :return:serializer object
        """
        queryset = self.get_object()  # 自動拿到pk並獲取到queryset
        serialize = self.get_serializer(queryset)
        return Response(serialize.data)

urls.py

from django.urls import path, include
from rest_framework import routers

from quickstart.views import UserViewSet, GroupViewSet, TestGroupViewSet

router = routers.DefaultRouter()
router.register("user", UserViewSet)
router.register("group", GroupViewSet)
router.register("test_group", TestGroupViewSet)

urlpatterns = [
    path("", include(router.urls)),
    path("api-auth/", include("rest_framework.urls", namespace="rest_framework"))
]

實際使用:session

相關文章
相關標籤/搜索