Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django custom manager request object/current user

Tags:

django

session

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)
like image 824
neolaser Avatar asked Jan 30 '11 22:01

neolaser


2 Answers

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!

like image 98
Bernhard Vallant Avatar answered Oct 19 '22 12:10

Bernhard Vallant


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

like image 20
andyshi Avatar answered Oct 19 '22 14:10

andyshi