我第一次使用django制作Rest API,我在该项目的网站上制作了该教程,但现在我对此表示怀疑,也没有找到明确的答案。
我正在制作的API具有基本终结点(例如:api.site.com/v1/videos/
)和其他依赖于嵌套配置的终结点(例如:api.site.com/v1/videos/<pk:video>/label/<pk:label>
)。
但是我正在使用视图集HyperlinkedModelViewSet和Rest框架中的模式。
所有嵌套结构都具有指向根端点的外键。因此,“标签”模型具有来自类别的外键。一个类别可以有多个标签。
这是我实际正在使用的代码:
from django.urls import path, include
from rest_framework import DefaultRouter
from API import views
from rest_framework.schemas import get_schema_view
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'videos', views.VideoViewSet)
router.register(r'categories', views.CategoryVieWSet)
schema_view = get_schema_view(title='Annotation Tool API')
# The API URLs are now determined automatically by the router.
urlpatterns = [
path('', include(router.urls)),
path('schema/', schema_view),
]
from API.models import User, Video, Category
from API.serializers import UserAPISerializer, VideoSerializer, CategorySerializer
from rest_framework import generics
from rest_framework import permissions
from rest_framework.decorators import api_view
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import renderers
from rest_framework import viewsets
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserAPISerializer
class VideoViewSet(viewsets.ModelViewSet):
queryset = Video.objects.all()
serializer_class = VideoSerializer
class CategoryVieWSet(viewsets.ModelViewSet):
queryset = Category.objects.all()
serializer_class = CategorySerializer
from rest_framework import serializers
from API.models import User, Video, Category, Label, Track, Annotation, Comment
from django.contrib.auth.models import User as djangoUser
class UserAPISerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'email', 'nickname', 'access', 'created_at',
'updated_at', 'deleted_at',
'usr_created', 'usr_updated', 'usr_deleted')
class VideoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Video
fields = ('id', 'extid', 'access', 'created_at', 'updated_at', 'deleted_at',
'created_by', 'updated_by', 'deleted_by')
class CategorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Category
fields = ('id', 'name', 'access', 'created_at', 'updated_at', 'deleted_at',
'created_by', 'updated_by', 'deleted_by', 'description', 'has_duration',
'settings', 'video')
我希望像这样调用“标签”端点:
显示所需类别的所有标签/创建新标签:api.site.com/v1/categories/<category:pk>/labels/
仅显示指定的标签/更新指定的标签:
api.site.com/v1/categories/<category:pk>/labels/<label:pk>
如何使用HyperlinkedModel和Schema实现该目标,或者应使用其他策略?如果还有其他麻烦的策略(例如使用ModelView或mixins),是否可以与我现在使用的策略混合?