Django REST,访问所选对象的方法

时间:2017-06-06 19:45:29

标签: django django-rest-framework

我的代码的这部分用[category_object] .subcats.all()填充查询集。让子元素成为类别对象的方法:

序列化器:

class CatSrlz(serializers.ModelSerializer):
class Meta:
    model = Category
    fields = ('id', 'label', )  

查看:

class CatsViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Category.objects.filter(parent=None)
serializer_class = CatSrlz

def retrieve(self, request, *args, **kwargs):
    # return Response({'res': self.kwargs})
    queryset = Category.objects.get(pk=str(self.kwargs['pk'])).subCats.all()
    dt = CatSrlz(queryset, many=True)
    return Response(dt.data)  

和网址:

router.register(r'cats', views.CatsViewSet)  

它有效,但我非常确定必须有更正确的方法 有吗?
感谢

1 个答案:

答案 0 :(得分:0)

检索单个对象时,可以在视图中使用get_object方法,该方法在DRF中如下所示,无需修改:

def get_object(self):
    """
    Returns the object the view is displaying.

    You may want to override this if you need to provide non-standard
    queryset lookups.  Eg if objects are referenced using multiple
    keyword arguments in the url conf.
    """
    queryset = self.filter_queryset(self.get_queryset())

    # Perform the lookup filtering.
    lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

    assert lookup_url_kwarg in self.kwargs, (
        'Expected view %s to be called with a URL keyword argument '
        'named "%s". Fix your URL conf, or set the `.lookup_field` '
        'attribute on the view correctly.' %
        (self.__class__.__name__, lookup_url_kwarg)
    )

    filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
    obj = get_object_or_404(queryset, **filter_kwargs)

    # May raise a permission denied
    self.check_object_permissions(self.request, obj)

    return obj

因此,您可以调整获得对象的部分:

filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
obj = get_object_or_404(queryset, **filter_kwargs)

并在那里添加你的subcat逻辑。

顺便说一句,我不知道你使用

的原因
dt = CatSrlz(queryset, many=True)

不应该“检索”返回单个对象吗?