【问题标题】:Django Rest Framework Nested View in Viewset视图集中的 Django Rest Framework 嵌套视图
【发布时间】:2018-08-31 09:22:07
【问题描述】:
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: from games.urls 将路由器作为游戏导入

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 2016-09-30
      • 2017-08-05
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      相关资源
      最近更新 更多