开发者

Django custom manager request object/current user

开发者 https://www.devze.com 2023-02-07 08:23 出处:网络
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 t

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 pu开发者_Python百科bManager(models.Manager):

    def get_queryset(self):        
        return pubEnt.objects.filter(state='new')

    def on_site(self):
        return pubEnt.objects.filter(state='old', val=0)


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!


Global Django requests http://nedbatchelder.com/blog/201008/global_django_requests.html

0

精彩评论

暂无评论...
验证码 换一张
取 消