如何通过ForeignKey查找字段而不是pk访问项目?

时间:2017-08-23 17:36:19

标签: django django-rest-framework

在django rest framework(DRF)中,我希望通过外键查找字段而不是pk访问项目 网址:\投资\<会员> \

while(!stack.isEmpty()) {
 int n = stack.pop();
 stack2.push(n);            
}

但有错误:

class InvestmentListViewSet(viewsets.ModelViewSet):
    queryset = Investment.objects.all()
    serializer_class = InvestmentSerializer
    lookup_field = 'member'

这是我的模型和序列化程序

investment.models.MultipleObjectsReturned: get() returned more than one 
Investment -- it returned 6!

如何使用外键会员返回投资清单?

1 个答案:

答案 0 :(得分:1)

针对当前问题的最佳解决方案,使用方法viewset为您的模型Member创建investments,如果不存在则创建 MemberSerializer

from rest_framework.decorators import detail_route


class MemberViewSet(viewsets.ModelViewSet):
    queryset = Member.objects.all()
    serializer_class = MemberSerializer

    @detail_route(methods=['get'], )
    def investments(self, request, pk):
        qs = self.get_object().investment_set.all()
        serializer = InvestmentSerializer(qs, many=True)
        return Response(serializer.data)
在urls.py中

router.register(r'member', MemberViewSet)

您可以通过网址/member/<member_pk>/investments/

获得结果

更多详情,extra-link-and-actions

希望对你有所帮助