简体   繁体   English

DRF-为PATCH请求创建多个端点

[英]DRF - creating multiple endpoints for PATCH request

I would like to create multiple endpoints for PATCH request. 我想为PATCH请求创建多个端点。

For eg. 例如。

class CityViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows city to be viewed or edited.
    """
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()
    queryset = City.objects.filter(active=True)
    serializer_class = CitySerializer

class CitySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = City
        fields = ('id', 'name', 'is_metro', 'is_village', 'active')

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if not isinstance(value, (list,dict)):
                setattr(instance, attr, value)

        instance.save()
        return instance

urls.py urls.py

router = routers.DefaultRouter()
router.register(r'city', CityViewSet)

Can I create multiple routers which finally go to PATCH request of this viewset only? 我是否可以创建多个路由器,这些路由器最终仅转到该视图集的PATCH请求? In the update method, based on the url, I will decide what to do. 在更新方法中,基于URL,我将决定要做什么。

You can register different url's for the same viewset, like: 您可以为同一视图集注册不同的网址,例如:

router = routers.DefaultRouter()
router.register(r'city', CityViewSet)
router.register(r'town', CityViewSet.as_view({'patch':'partial_update'})

If you're using a browsable API and DRF is creating reverse urls, you will probably get the first ones there (in the example above - with 'city') 如果您使用的是可浏览的API,并且DRF正在创建反向网址,则您可能会在其中找到第一个网址(在上面的示例中,带有“ city”)

If you want only PATCH with the second link, then doing .as_view({'patch':'partial_update'}) will prevent from reaching it with other methods, as it will throw MethodNotAllowed if you will try to reach it with any other method. 如果只希望使用第二个链接的PATCH,则执行.as_view({'patch':'partial_update'})可以防止其他方法访问它,因为如果尝试使用任何其他方法访问它,它将抛出MethodNotAllowed 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM