我对 Django 休息框架相当陌生,我有几个问题可以为我解决很多问题。
我正在查看简单的 CRUD 通用 View 的文档,例如 ListAPIView、Retrieve... 等。
对于我的 ListView ,我是这样创建的:
class CourseListApiView(ListAPIView):
queryset = Course.objects.all()
serializer_class = CourseListSerializer
这是有道理的,因为查询集返回 Course.objects.all() 所以所有的类(class)都会出现。
我不清楚的是 RetrieveApi 中的查询集是如何工作的
class CourseRetrieveAPIView(RetrieveAPIView):
queryset = Course.objects.all()
serializer_class = CourseRetrieveSerializer
这是我的检索 View ,它从我的链接中获取 pk 并返回相应的类(class)。我不清楚的是为什么查询集是 Course.objects.all(),而不是从 URL 获取 kwargs 并过滤我的类(class)的过滤查询。我按照自己的方式尝试并得到了相同的结果,我的观点是:
class CourseRetrieveAPIView(RetrieveAPIView):
serializer_class = CourseRetrieveSerializer
def get_queryset(self):
queryset = Course.objects.filter(pk=self.kwargs.get('pk'))
return queryset
这更有意义,因为查询集是 Course.objects.filter(pk=self.kwargs.get('pk')) 而不是 Course.objects.all() 这对我来说没有意义,因为我正在过滤我的类(class)通过 URL 中的 pk
希望我的问题是有道理的。如果您需要任何说明,请发表评论。我知道答案很明显,但我对这个框架很陌生
最佳答案
您将不得不通过 rest_framework
的代码库.一个名为 get_object
的函数使用两个名为 lookup_field
的类变量和 lookup_url_kwarg
默认值为 pk
和 None
分别。
摘自GenericAPIView
在 rest_framework/generics.py
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
如您所见
lookup_url_kwarg
设置为等于 lookup_field
如果没有指定。如果您将此值更改为您要求的字段,则过滤器 get_object_or_404
变化。现在回到您的问题,当您使用
url kwargs
手动指定过滤器时您没有使用 RetrieveAPIView
提供的功能.相反,您正在做的是用 pk
过滤掉您的结果。来自 url kwargs
在 get_queryset
然后将该 QuerySet 结果发送到 get_object
这将再次为您做同样的事情。
关于python - Django 休息框架。检索的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46860183/