使用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「:」「}
對於任何其他自定義調用,您可以將其他方法添加到主Vie通過DRF裝飾器設置(detail_route,list_route)。但遵循這種模式,您可以構建健壯的API。