查看仅当前用户对象的列表,Django REST [英] View list of only current user objects, Django REST

查看:32
本文介绍了查看仅当前用户对象的列表,Django REST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个视图:/notes/和/notes//在 models.py 中的注释模型中,我具有所有者变量,该变量存储所有者的登录名.因为我想拥有许多用户,所以我不希望他们看到其他人的注释,所以我创建了权限:

I have 2 views: /notes/ and /notes// In note model in models.py I have owner variable, that stores owner's login. Because I want to have many users, I don't want them to see other's notes, so I created the permission:

class IsOwner(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj.owner == request.user

我将此权限设置为 NotesList(generics.ListCreateAPIView) NotesDetail(generics.RetrieveUpdateDestroyAPIView).现在,如果用户要转到/notes/< pk>/,则无法查看其他人的注释,但是在/notes/中,他仍然可以查看完整列表.那么,我该如何更改呢?我只想在笔记列表中看到我的笔记.我认为正确的方法是过滤 queryset = Snippet.objects.all().filter(owner = ...),但不能马上考虑.

I set this permission to NotesList(generics.ListCreateAPIView) and NotesDetail(generics.RetrieveUpdateDestroyAPIView). Now user can't view other's notes if he will go to /notes/<pk>/, but in /notes/ he can view the full list anyway. So, how can I change it? I want to see in notes list only my notes. I think the right way is to filter queryset = Snippet.objects.all().filter(owner=...) but can't think right away.

推荐答案

您是正确的,需要在列表视图中覆盖查询集.但是您不能在 queryset 属性本身中执行此操作,因为它是在流程启动时执行的,而您需要访问仅在请求时可用的数据.因此,您需要在该视图中定义 get_queryset 方法:

You are correct, you need to override the queryset in the list view. But you can't do that in the queryset attribute itself, because that is executed at process startup whereas you need access to data that is only available at request time. So you need to define the get_queryset method in that view:

def get_queryset(self, *args, **kwargs):
     return Snippet.objects.all().filter(owner=self.request.user)

这篇关于查看仅当前用户对象的列表,Django REST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆