In general, this violates the logic of Django. There it is proposed to drag the Request
object manually, and, yes, to do Client.objects.filter(user=request.user)
. If this is done many times, you can in fact in the function to issue:
# models.py ... def own_clients(request): return Client.objects.filter(user=request.user) ...
And, accordingly, use:
# views.py from .models import ..., own_clients ... ... = own_clients(request).all()
On the other hand, in principle, make a copy of the request
local to the stream:
# middleware.py import threading _local_storage = threading.local() class CurrentRequestMiddleware(object): def process_request(self, request): _local_storage.request = request def get_current_request(): return getattr(_local_storage, "request", None) def get_current_user(): request = get_current_request() if request is None: return None return getattr(request, "user", None)
In settings.py
add to MIDDLEWARE_CLASSES
this CurrentRequestMiddleware
and then use it as you do:
# models.py from django.db import models from .middleware import get_current_user class OwnManager(models.Manager): def get_queryset(self): qs = super(OwnManager, self).get_queryset() return qs.filter(user=get_current_user()) class Client(models.Model): ... own_objects = OwnManager()
But all this will work until the internal structure of the framework changes, and no one gave a guarantee for each request to create a separate thread (although in fact this seems to be the case). For example, I would not vouch for the performance of this when used in conjunction with django-gevent.