【问题标题】:Django REST Generic View for related model相关模型的 Django REST 通用视图
【发布时间】:2017-11-01 20:09:07
【问题描述】:

我有一个类似的设置 - 一个食谱类,它有多个食谱。

我有一个

class CookbookListCreateView(ListCreateAPIView):
    permission_classes = (IsAuthenticated,)
    queryset = Cookbook.objects.all()
    serializer_class = CookbookSerializer

这会处理创建/列出食谱。

我需要一个 ListCreateView 用于 Recipe 模型,但该列表必须属于特定的食谱,因此该网址:

/cookbook/2/recipes

只会返回 pk 为 2 的食谱中找到的食谱。

如何修改ListCreateAPIView 以遵循此行为?

【问题讨论】:

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


    【解决方案1】:

    你可以创建一个新的路由/url: /cookbook/<cookbook_pk>/recipes

    还有一个你想要的 api 视图:

    class RecipeListCreateView(ListCreateAPIView):
        permission_classes = (IsAuthenticated,)
        queryset = Recipe.objects.all()
        serializer_class = RecipeSerializer
    
        def get_cookbook(self):
            queryset = Cookbook.objects.all()
            return get_object_or_404(queryset, pk=self.kwargs['cookbook_pk'])
    
        def get_queryset(self):
            cookbook = self.get_cookbook()
            return super().get_queryset().filter(cookbook=cookbook)
    
        def perform_create(self, serializer):
            cookbook = self.get_cookbook()
            serializer.save(cookbook=cookbook)
    

    在需要食谱时使用get_cookbook(例如,在上述perform_create 方法中)

    【讨论】:

      【解决方案2】:

      这就是 DRF 中所谓的“详细路线”。

      class CookbookListCreateView(ListCreateAPIView):
          ....
      
          @detail_route(methods=['get'])
          def recipes(self, request, **kwargs):
              # Do what you would do in a function-based view here
      

      这对于简单的情况就足够了,但在更复杂的视图中,使用DRF-extensionsnested route 功能是更好的解决方案。

      【讨论】:

        猜你喜欢
        • 2021-07-07
        • 2018-12-02
        • 2014-04-24
        • 2018-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-17
        • 2017-12-24
        相关资源
        最近更新 更多