我正在 Django / DjangoRestFramework 中工作,尝试使用额外的操作来构建可路由的外键。我收到以下错误,我相信它与 上的 create 方法有关FinancialsSerializer,或缺乏该方法,但我不确定web_1 | AttributeError: 'dict' object has no attribute 'pk'股票视图集 19 class StockViewSet(viewsets.ModelViewSet): 20 queryset = Stock.objects.all() 21 serializer_class = StockSerializer 22 lookup_url_kwarg = "ticker" 23 lookup_field = "ticker__iexact" 24 25 @action(detail=True, methods=["POST", "GET"]) 26 def financials(self, request, ticker=None): 27 if request.method == "GET": 28 stock = self.get_object() 29 financials = stock.get_financials() 30 financials = FinancialsSerializer(financials) 31 return Response(financials.data) 32 if request.method == "POST": 33 serializer = FinancialsSerializer(request.data) 34 financials = Financials.objects.create(serializer.data) 35 financials.save()财务序列化器 9 class FinancialsSerializer(WritableNestedModelSerializer): 10 balance_sheet = BalanceSheetSerializer() 11 income_statement = IncomeStatementSerializer() 12 cashflows_statement = CashflowsStatementSerializer() 13 14 class Meta: 15 model = Financials 16 fields = ["balance_sheet", "income_statement", "cashflows_statement"]
1 回答
慕后森
TA贡献1802条经验 获得超5个赞
我在您的代码中发现了几个问题。
首先,对于GET
方法:
serializer = FinancialsSerializer(financials, many=True) return Response(serializer.data)
二、对于POST
方法:
serializer = FinancialsSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save()return Response(serializer.data)
- 1 回答
- 0 关注
- 77 浏览
添加回答
举报
0/150
提交
取消