@list_route装饰器REST框架

时间:2015-10-31 17:13:07

标签: django django-rest-framework

考虑这个模型:

def Vote(models.Model):
    player = models.ForeignKey(Player)
    target = models.ForeignKey(Player)

现在,我有一个ViewSet:

class VoteViewSet(viewsets.ModelViewSet):
    queryset = Vote.objects.all()
    serializer_class = VoteSerializer

我注册了一个路由器:

api_router = routers.SimpleRouter()
api_router.register(r'votes', VoteViewSet)

这样我就可以访问以下资源:

http://example.com/api/votes             # lists all votes
http://example.com/api/votes/1/          # return vote with pk=1

如何使用像

这样的网址创建一个返回玩家给出和接收的所有投票的路线
http://example.com/api/votes/players/1/   # ?

我会尝试这样做,但是......

class VoteViewSet(viewsets.ModelViewSet):
     queryset = Vote.objects.all()
     serializer_class = VoteSerializer

     @detail_route()
     def players(self, request):
         # Here I need to access player id in the url!

1 个答案:

答案 0 :(得分:0)

您可以在视图集上定义lookup_field属性,以便它通过player_id字段过滤投票查询集。

class PlayerVotesViewSet(viewsets.ModelViewSet):
    queryset = Vote.objects.all()
    serializer_class = VoteSerializer
    lookup_url_kwarg = 'player_id'
    lookup_field = 'player_id'

然后在您的路由器中,您应该将路径定义为:

api_router.register(r'votes/players', PlayerVotesViewSet)