如何使用 Serializer 从 api 中删除 [POST]/api/contact/{pk}/
? (去掉第二个API)
我的序列化器定义如下:
class ContactSerializer(serializers.ModelSerializer):
class Meta:
model = Contact
fields = ('chatuser', 'contact', 'is_blocked')
我的ViewSet如下:
class ContactViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
queryset = Contact.objects.all()
serializer_class = ContactSerializer
最佳答案
您也许可以使用 ReadOnlyModelViewset?来自文档:
http://www.django-rest-framework.org/api-guide/viewsets#readonlymodelviewset
The ReadOnlyModelViewSet class also inherits from GenericAPIView. As with ModelViewSet it also includes implementations for various actions, but unlike ModelViewSet only provides the 'read-only' actions, .list() and .retrieve().
这有点奇怪,因为 GenericViewSet 不应该为您提供任何开箱即用的操作,您应该只使用 ModelViewSet 获取 POST。
The GenericViewSet class inherits from GenericAPIView, and provides the default set of get_object, get_queryset methods and other generic view base behavior, but does not include any actions by default.
这可能意味着这些 mixin 之一正在为您提供额外的操作,请参阅:
In order to use a GenericViewSet class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly.
如果您可以检查这些 mixins 的定义或将它们发布到此处,或者尝试使用 ReadOnlyModelViewSet 而不使用任何 mixins,看看您的进展如何。
关于 Django 休息 : How to disable the POST api with {pk},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21655672/