简体   繁体   中英

Multiple vs one big context_processor

I have multiple context processor and in each I have to request the user. Each of these look like this:

def UploadForm(request):
  user = request.user
  Uplo = UploadForm(request.POST or None, initial={user})
  return {'Uplo': Uplo}

I saw that this is not efficient since im requesting the user multiple times, so I thought about writing one big context processor where I define all the Forms at once.

def AllForms(request):
  user = request.user
  Uplo = UploadForm(request.POST or None, initial={user...})
  SetForm = SetForm(request.POST or None, initial={user...})
  ...
  return {'Uplo': Uplo,'SetForm': SetForm}

Can anybody tell me if I gain here anything? What is the common standard for context processors? I could not find anything on SO.

Getting user from request is not a big thing. It is o(1) operation.

However if the multiple context processors are not doing different thing and can be don at one time, it should be better to create one big context processor as you say it. The reason being you have to get in and out of the function multiple times in same request.

Anyway if you want definitive difference, you can just print time in multiple and clubbed context processors.

And yes, if you are hitting the database every time, you should club them and optimise the number of times you have to hit the db.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM