使用 DRF,您可以遵循与此类似的模式。
models.py
class Foo(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=50)
class Meta:
unique_together = ('user', 'slug')
serializers.py
from rest_framework import serializers
from .models import Foo
class FooSerializer(serializers.ModelSerializer):
class Meta:
model = Foo
views.py
from rest_framework.permissions import IsAuthenticated
from .models import Foo
from .serializers import FooSerializer
class FooViewSet(viewsets.ModelViewSet):
serializer_class = FooSerializer
permission_class = (IsAuthenticated, )
queryset = Foo.objects.all()
routers.py
from rest_framework.routers import DefaultRouter
from .views import FooViewSet
router = DefaultRouter()
# registers viewset to url
router.register(r'foos', FooViewSet)
这样,您将拥有以下端点:
GET /foobars - 检索所有 foobar 对象添加 pk 并获取详细视图
POST /foobars - 创建 foobar 对象`{"user": "", "title": "", "slug": ""}
对于任何其他自定义调用,您可以通过 DRF 装饰器(detail_route,list_route)向主 ViewSet 添加其他方法。但是按照这种模式,您可以构建强大的 API。