1

我正在使用 Django 和 Django Rest Framework 构建 API

我有以下端点:
host/products/指向ModelViewSet,所以我有一个为指定模型工作的 CRUD。

此外,我使用以下代码为名为config的嵌套模型定义了一个额外的操作:

@action(detail=False, methods=['get', 'post'])
def config(self, request, *args, **kwargs):

    if request.method == 'GET':
        return super().list(request, *args, **kwargs)

    elif request.method == 'POST':
        return super().create(request, *args, **kwargs)

创建的 URL 为: host/products/config/

在此 URL,我可以在第二个指定模型中创建和列出对象

问题是我想为嵌套 URL 包含PATCHDELETE方法,我的意思是:
host/products/config/ detail /

我尝试做这样的事情:

@action(detail=True)
@config.mapping.patch
def update_config(self, request, *args, **kwargs):
    return super().update(request, *args, **kwargs)

但是,当然,它不起作用......

如何将详细信息操作映射到同一视图集中的另一个操作?

完整代码如下:

class ProductViewSet(viewsets.ModelViewSet):

def get_permissions(self):
    ''' Assign permissions based on action. '''
    if self.action in ['suggestions']:
        permission_classes = [AllowAny]
    else:
        permission_classes = [AllowAny] # [IsAdminUser | IsDevUser]
    return [permission() for permission in permission_classes]

def get_queryset(self):
    ''' Return queryset based on action. '''
    if self.action == 'config':
        # Return product details
        return ProductDetails.objects.filter(active=True)
    else:
        # Return active products
        return Product.objects.filter(active=True)

def get_serializer_class(self):
    ''' Return serializer based on action. '''
    if self.action == 'suggestions':
        return SurveySerializer
    elif self.action == 'config':
        return ProductDetailModelSerializer
    else:
        return ProductModelSerializer

@action(detail=False, methods=['get', 'post'])
def config(self, request, *args, **kwargs):

    if request.method == 'GET':
        return super().list(request, *args, **kwargs)

    elif request.method == 'POST':
        return super().create(request, *args, **kwargs)

@action(detail=True)
@config.mapping.patch
def update_config(self, request, *args, **kwargs):
    return super().update(request, *args, **kwargs)
4

0 回答 0