我一直在尝试使用django-filters,但是对象没有被过滤。另外,该权限不适用于 partial_update 视图
我有一个Viewset,它具有一些基本动作,例如-list(),retrieve(),destroy(),partial_update()和其他一些动作,并尝试对其应用过滤器。
经过一些研究,我发现由于我是通过过滤器创建查询集的,所以我将不得不覆盖 get_queryset()方法。但是,这似乎也不起作用。过滤器仅适用于 ModelViewSet 或 ListApiView 吗?
ViewSet-
class PostViewSet(viewsets.ViewSet):
"""
The Endpoint to list, retrieve, create and delete Posts.
"""
filter_backends = (DjangoFilterBackend, )
# filterset_class = PostFilter
filter_fields = ('pet_age', 'pet_gender', 'breed')
def get_permissions(self):
if self.action == 'partial_update' or self.action == 'update':
permission_classes = [IsPostAuthor, ]
elif self.action == 'create' or self.action == 'destroy':
permission_classes = [IsAuthenticated, ]
else:
permission_classes = [AllowAny, ]
return[permission() for permission in permission_classes]
def get_queryset(self):
return Post.objects.active() # This is implemented via custom Manager
def list(self, request, *args, **kwargs):
"""
Method for Post listing. It can be accessed by anyone.
"""
serializer = PostListSerializer(self.get_queryset(), many=True, context={"request": request})
return Response(serializer.data)
# REST CODE TRUNCATED
权限-
class IsPostAuthor(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
if request.user.is_authenticated:
if view.action in ['partial_update', 'update']:
return obj.user.id == request.user.id
return False
return False
PostFilter-
class PostFilter(filters.FilterSet):
class Meta:
model = Post
fields = ('pet_age', 'pet_gender', 'breed', )
经理-
class PostManager(models.Manager):
def active(self):
return self.filter(post_status='Active')
我们将不胜感激任何帮助。
答案 0 :(得分:1)
好的,终于找到了DRF Docs的解决方案。问题在于,对于普通的ViewSet,您必须重写方法 filter_queryset()并相应地返回相应的 queryset 。然后使用Aman所述的 filter_queryset 下的 queryset -
serializer = PostListSerializer(self.filter_queryset(self.get_queryset()), many=True, context={"request": request})
以下是仍面临问题的人员的参考代码-
filter_queryset-
def filter_queryset(self, queryset):
filter_backends = (DjangoFilterBackend, )
# Other condition for different filter backend goes here
for backend in list(filter_backends):
queryset = backend().filter_queryset(self.request, queryset, view=self)
return queryset
答案 1 :(得分:0)
您已经覆盖了list方法,因此无法调用filter_queryet方法。
def list(self, request, *args, **kwargs):
"""
Method for Post listing. It can be accessed by anyone.
"""
serializer = PostListSerializer(self.filter_queryset(self.get_queryset()), many=True, context= .
{"request": request})
return Response(serializer.data)