gpt4 book ai didi

python - 如何在 django rest 框架 generics.RetrieveAPIView 中使用限制

转载 作者:太空狗 更新时间:2023-10-29 22:10:57 24 4
gpt4 key购买 nike

由于 django rest 框架中的 generics.RetrieveAPIView 应该只返回一条记录,我想在 get 查询方法中使用限制,如下所示

class PortUserView(generics.RetrieveAPIView):
lookup_field = 'user'

def get_queryset(self):

return PortUser.objects.all()[:1]

出现类似这样的错误“一旦切片已被获取,就无法过滤查询”。

我的代码有什么问题?

最佳答案

您无需担心在retrieve 时从查询集中返回单个对象。 DRF 将使用其在 GenericAPIView 中定义的 .get_object() 为您自动处理 .

您只需使用以下代码,DRF 就会为您处理retrieve 操作。

class PortUserView(generics.RetrieveAPIView):
lookup_field = 'user'
queryset = PortUser.objects.all()

get_object(self)

Returns an object instance that should be used for detail views. Defaults to using the lookup_field parameter to filter the base queryset.

retrieve 操作的源代码:

def retrieve(self, request, *args, **kwargs):
instance = self.get_object() # here the object is retrieved
serializer = self.get_serializer(instance)
return Response(serializer.data)

我们可以看到 DRF 使用 .get_object() 函数从查询集中获取对象。为了执行过滤,它使用 View 中定义的 lookup_field

这里是实际的 get_object() 代码,使事情更清楚。

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) # <-- can see that filtering is performed on the base of 'lookup_field'

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

return obj # will return the single retrieved object

关于python - 如何在 django rest 框架 generics.RetrieveAPIView 中使用限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31876213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com