简体   繁体   English

当用户位于管理页面上时,Django自定义管理器将返回所有内容

[英]Django custom manager return everything when user is on admin page

I'm creating a Django app. 我正在创建Django应用。 It's an article app. 这是一个文章应用程序。 I have a field named hidden and I want to return a queryset without articles when hidden is true and the user isn't in the admin panel. 我有一个名为hidden的字段,当hidden为true 用户不在管理面板中时,我想返回一个没有文章的查询集。

Admin-page -> Show everything 管理员页面->显示所有内容

Normal search -> Show only with hidden = False 普通搜索->仅在hidden = False时显示

My "Normal Search" is a custom search I made. 我的“常规搜索”是我进行的自定义搜索。 I'm filtering results with django-filter and I want to automatically filter out hidden articles. 我正在用django-filter过滤结果,我想自动过滤掉隐藏的文章。

I'm creating this with a custom manager: 我正在使用自定义管理器创建此文件:

class ArticleManager(models.Manager):
    def get_queryset(self, request):
        if request.user.is_superuser:
            return super().get_queryset()
        return super().get_queryset().filter(hidden=False)

but I'm just getting this error: 但我刚得到这个错误:

TypeError: get_queryset() missing 1 required positional argument: 'request'

Usually no request instance would get passed to manager methods. 通常,没有request实例将传递给管理器方法。 But you can customize the queryset used inside an admin using its get_queryset() method : 但是您可以使用其get_queryset()方法来自定义管理员内部使用的get_queryset()

class ArticleAdmin(admin.ModelAdmin):
    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(hidden=False)

Note that this queryset will also get for editing instances, so you can really restrict which objects are accessible for certain users. 请注意,此查询集也将用于编辑实例,因此您可以真正限制某些用户可以访问哪些对象。

Based on the updated question: You shouldn't redefine the model manager's get_queryset function signature to take a request parameter. 基于更新的问题:您不应重新定义模型管理器的get_queryset函数签名以接受request参数。 Instead, you need to create a new manager function with a user parameter which will return only the items you want. 相反,您需要使用user参数创建一个新的管理器函数,该函数仅返回所需的项目。 You will then use that as the queryset to your filter. 然后,您将使用它作为queryset到过滤器。

For example: 例如:

class ArticleManager(models.Manager):
    def get_visible_items(self, user):
        if user.is_superuser:
            return super().get_queryset()
        return super().get_queryset().filter(hidden=False)

# In your view:
user = request.user
artice_filter = ArticleFilter(queryset=Article.objects.get_visible_items(user))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM