аватар question@mail.ru · 01.01.1970 03:00

Access to Request.user from the Django model

I am writing a site on Django. There is such a problem: there is a Client model for almost everywhere on the site the user must display his customers. At first, I wrote in every form like this:

  client.objects.  Filter  (User = Request.user)     

Then I made his manager with the method to which you need to transmit the user, but in general it does not relieve the problem to constantly transfer the user. How can you make a current user available in Models.py?

аватар answer@mail.ru · 01.01.1970 03:00

In general, this violates the logic of the DJango work. It is proposed to carry an object request manually, and, yes, do client.objects.filter (user = request.user) . If this is done many times, you can also arrange in the function:

  # models.py    def   open_clients  ( readst ):   Retu  Client.objects.  filter  (user = redest.user)  ...     

and, accordingly, use:

  # views.py    from  .models  IMPort  ..., OWN_CLIENTS ...  ... WN_CLENTS (REQUEST). Class = ""> all  ()     

on the other hand, in principle, make a copy of the request local for the stream:

  # Middleware.py    Import  Threading_Local_Storage.local ()   class   Currentrequestmiddleware  ( object ):   def   Process_request  ( self, request ):  _local_storage.request = request  def   get_current_request  ():   retu   getttr  (_ local_storage,  "" redest "" ,  none )   def   get_current_user  ():  request get_current_request ()   if  request  is   none :   retu   none    retu   getttr  (recoest, ,  none )  

in settings.py add to midleware_classes this CurrentrequestMiddleware and then use, like yours:

  # ""># models.py    from  django.db  import  models  from  .midleware  Import  get_current_user  class   Ownmanager  (Models.manager):   Def   get_queryseet  ( self ):  qs =  super  (Ownmanager, self) .get_querySet ()   retu  qs.  filter  (user = get_current_user ())   class   Client  (models.model):  ...  own_objects = Ownmanager ()     

But all this will work until the inteal device of the framework, and the guarantees that no one is created for each request, no one is created a separate stream He gave (although in fact this seems to be so). For example, I would not have entrusted for the performance of this when using it with Django-Geent.

Latest

Similar