You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ModelViewSet中post方法生效但perform_create无效的原因咨询

问题原因分析

你遇到的问题核心在于Django REST Framework中ModelViewSet的默认路由规则和方法绑定逻辑:

1. perform_create的触发条件

ModelViewSet里的perform_create是被create方法调用的,而create方法默认只对应集合路由(比如/products/)的POST请求——这个请求的作用是创建新的Item对象,和你要给指定商品(通过pk)加购物车的需求完全不匹配。

你实际是在详情路由(比如/products/<pk>/)上发送POST请求,但ModelViewSet的默认路由里,详情路由并没有绑定create/perform_create方法,所以你写的perform_create根本不会被触发。

2. 自定义post方法生效的原因

当你在ViewSet中定义了post方法时,DRF会自动把详情路由的POST请求绑定到这个自定义方法上,所以请求到达时会直接执行你的购物车逻辑,功能自然正常。

更规范的实现方式

如果想遵循DRF的最佳实践,建议用@action装饰器自定义动作,避免和默认方法冲突:

from rest_framework.decorators import action

class Product_List(viewsets.ModelViewSet):
    permission_classes = [IsAuthenticated, ] 
    queryset = Item.objects.all()
    serializer_class = ProductListSerializer

    @action(detail=True, methods=['post'])
    def add_to_cart(self, request, pk=None):
        items = get_object_or_404(Item, id=pk)
        if items.discount_price < items.price:
            ncart = CartItem.objects.create(user=request.user, product=items)
            ncart.total = ncart.quantity * items.discount_price
            ncart.save()
        else:
            ncart = CartItem.objects.create(user=request.user, product=items)
            ncart.total = ncart.quantity * items.price
            ncart.save()
        return Response({'msg': 'Product Added to Cart Successfully'}, status=status.HTTP_200_OK)

这样会生成路由/products/<pk>/add_to_cart/,语义更清晰,也不会干扰ModelViewSet的默认方法逻辑。

内容的提问来源于stack exchange,提问作者Naga Rajan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 19:05:27