我是 DJango 和 DRF 的新手,并被要求管理一些 DJango/DRF 相关代码。经过大量搜索后,我仍然无法找到有关 filter_queryset 如何工作以及如何与不同参数一起使用的完整示例。
在某些地方我看到它的用法如下:
self.filter_queryset(queryset)
在其他地方,它与一些参数一起使用。如果有人能够解释基本原理,例如如何以及何时使用它、什么是因变量(lookup_field、filter_backends 等...)和参数以及如何设置它们,那将会很有帮助。
我进行了很多搜索,也浏览了文档。如果我错过了任何医生,请告诉我。
The filter_queryset()- (源代码) https://github.com/encode/django-rest-framework/blob/master/rest_framework/generics.py#L142是一种最初在中实现的方法GenericAPIView--(DRF 文档) https://www.django-rest-framework.org/api-guide/generic-views/ class.
def filter_queryset(self, queryset):
"""
Given a queryset, filter it with whichever filter backend is in use.
You are unlikely to want to override this method, although you may need
to call it either from a list view, or from a custom `get_object`
method if you want to apply the configured filtering backend to the
default queryset.
"""
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
我认为该方法的功能从文档字符串中清晰可见。
“......在其他地方它与一些参数一起使用”
The views
's filter_queryset()
方法只需要一个参数,即queryset
进行过滤。
But, filter-backends
' filter_queryset()
方法采用三个参数,分别是request
,queryset
和view
itself.
什么是过滤器后端?
Filterbackends 是帮助我们通过复杂的查找和其他一些东西来过滤查询集的类。
DRF 几乎没有内置后端可以在这里找到 https://github.com/encode/django-rest-framework/blob/master/rest_framework/filters.py.DRF官方文档推荐使用django-filter https://django-filter.readthedocs.io/en/master/用于高级过滤目的的包。
过滤器后端如何工作?
看一下源代码DjangoFilterBackend https://github.com/carltongibson/django-filter/blob/master/django_filters/rest_framework/backends.py#L20类及其方法...它是filter_queryset(...)
方法在过滤过程中起着关键作用。
我建议阅读以下文档Django 过滤器 https://django-filter.readthedocs.io/en/stable/通过更多示例来理解相同的用法。
通过定义filterset_class https://django-filter.readthedocs.io/en/master/guide/rest_framework.html#adding-a-filterset-with-filterset-class,您可以更好地控制过滤过程(例如提供lookup_expr
etc)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)