如何在同一 URL 中查询模型字段元素

How to Query model filed elements in the same URL

我正在用 DRF 编写单个模型应用程序。我的模型如下所示:

class Superhero(models.Model):
    squad_name = models.CharField(max_length=100)
    hometown = models.CharField(max_length=30)
    formed = models.DateField()
    active = models.BooleanField()
    members = JSONField()

我的视图集如下所示:

class SuperheroViewSet(viewsets.ViewSet):
    """
    A simple ViewSet for listing or retrieving superheros.
    """
    serializer_class = SuperheroSerializer

    def list(self, request):
        """list superhero object"""
        queryset = Superhero.objects.filter()
        serializer = SuperheroSerializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        queryset = Superhero.objects.filter()
        superhero = get_object_or_404(queryset, pk=pk)
        serializer = SuperheroSerializer(superhero)
        return Response(serializer.data)

最后,我的路由器是:

router = DefaultRouter()
router.register(r'superhero', SuperheroViewSet, basename='superhero')
urlpatterns = router.urls

现在我该如何设置 URL,所以我会像这样查询成员字段: //superhero/{id}/members 获取特定id成员。我试过 drf nested URL 但没有用。 url 我有 superhero/ 和 superhero/{id} 的作品。

你应该使用 detailed viewset action.

您的代码看起来像这样:

from rest_framework.decorators import action
from rest_framework.shortcuts import get_object_or_404
from rest_framework.response import Response

class SuperheroViewSet():
...

    @action(detail=True, methods=['get'], url_path='members')
    def get_superhero_members(self, request, pk=None):
        superhero = get_object_or_404(self.get_queryset(), pk=pk)
        members = <get members of your hero>
        return Response(members)

您可能还应该为成员和响应使用自定义序列化程序 return:return Response(CustomSerializer(members).data)