问题
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)
回答1:
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
!
回答2:
Global Django requests http://nedbatchelder.com/blog/201008/global_django_requests.html
来源:https://stackoverflow.com/questions/4846152/django-custom-manager-request-object-current-user