Django Rest Framework在Viewset中的嵌套视图

时间:2018-08-31 09:22:07

标签: python django rest api django-rest-framework

class GameInviteViewSet():
    queryset = Game.objects.all()
    serializer_class = GameSerializer

    @action(
        methods=['get'],
        detail=True,
    )
    def invite(self, request, **id):
        # Invite user here with endpoint /api/games/{id}/invite/{user}

我如何制作上述端点?我可以输入/api/games/{id}/invite/,但是如何在此之后添加另一个参数。

或者,根据文档,默认情况下为

{prefix}/{lookup}/{url_path}/   

我想要

{prefix}/{lookup}/{url_path}/{prefix2}/{lookup2}/{url_path2}/   

{prefix}/{lookup}/{url_path}/{lookup2}/{url_path2}/

这样我就可以做

games/{id}/{invite}/{user}/
games/{id}/{kick}/{user}/
games/{id}/{players}/{user}/gamestats/

要注册我的路由器,请执行以下操作:

games/urls.py

router = routers.DefaultRouter()
router.register(r'^api/games', GameViewSet, 'games')

api/urls.py:     从games.urls将路由器导入为游戏

router = routers.SimpleRouter()
urlpatterns += games.urls

2 个答案:

答案 0 :(得分:0)

如下定义 invite()

class GameInviteViewSet():
    queryset = Game.objects.all()
    serializer_class = GameSerializer

    @action(methods=['get'], detail=True)
    def invite(self, request, id, user, *args, **kwargs):
        ......
        ......
        ......

并在您的games/urls.py

# games/urls.py
router = routers.DefaultRouter()
router.register(r'^api/games', GameViewSet, 'games')
urlpatterns = [
    url(r'api/games/(?P<id>\d+)/invite/(?P<user>\d+)$'),

]

示例端点: /api/games/123/invite/765/

答案 1 :(得分:0)

DRF Nested Routers是一个模块,可用于在Django Rest Framework中定义嵌套资源。

它有超过700个GitHub星,并且是mentioned in the official documentation