Django自定义管理器请求对象/当前用户(Django custom manager request object/current user)

编程入门 行业动态 更新时间:2024-10-24 20:11:24
Django自定义管理器请求对象/当前用户(Django custom manager request object/current user)

我通过创建一个继承自models.Manager的类来创建自定义管理器。管理器只是更改了默认的model.objects查询以添加一些过滤器。 现在,我想根据用户登录添加一个过滤器。我不想通过代码更改添加什么参数搜索,有没有什么办法可以得到请求对象/当前用户,而不必传递给方法?

我希望这不是一个愚蠢的问题,但我可能会感到困惑...

这是管理器的基本设置

class pubManager(models.Manager): def get_queryset(self): return pubEnt.objects.filter(state='new') def on_site(self): return pubEnt.objects.filter(state='old', val=0)

I have made a custom manager by creating a class inheriting from models.Manager.The manager just changed the default model.objects query to add some filters. Now, I want to add a filter according to the user logged in. I dont want to have to search through code changing what params are added, is there any way I can get the request object/current user without passing it through to the method?

Im hoping this is not a stupid question, but I may just be getting confused...

This is the basic setup of the Manager

class pubManager(models.Manager): def get_queryset(self): return pubEnt.objects.filter(state='new') def on_site(self): return pubEnt.objects.filter(state='old', val=0)

最满意答案

django没有办法在不通过它的情况下访问当前request 。 如果没有它,你可能应该重新考虑你的设计! 有权访问request不应该是管理者方法的要求,因为它也可以从没有request对象的地方访问(比如从python shell调用方法)。 如果您需要访问当前登录的用户,请将user对象传递给方法(来自request.user ),但不传递整个request !

There is no way in django to access the current request without passing it. If can't live without it you should probably rethink your design! Having access to the request shouldn't be a requirement of a manager's method, since it could also be accessible from somewhere where you do not have a request object (think for example of calling the method from the python shell). If you need access to the currently logged-in user, pass the user object to the method (from request.user), but not the whole request!

更多推荐

本文发布于:2023-07-04 16:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1026875.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   管理器   对象   用户   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!