什么时候适合使用Django上下文处理器?

问题描述:

如果大约一半的视图需要相同的数据集,那么使用上下文处理器来使数据总是可用,还是有更好的方法来避免重复代码以跨多个视图获取数据,而无需查询数据是否不会在视图中使用?

If about half of my views require the same data set, is it appropriate to use a context processor to make the data always available, or is there a better way to avoid repeating the code to get that data across several views without querying the data if it won't be used in the view?

RequestContext initializer将运行设置文件中列出的任何上下文处理器,但它还需要运行其他处理器的列表。任何通用上下文处理器都可以放在settings.py中,更具体的可以根据具体情况添加到 RequestContext 中。

The RequestContext initializer will run any context processors listed in the settings file, but it also takes a list of additional processors to run. Any general purpose context processors can be put in settings.py and more specific ones can be added to the RequestContext on a case-by-case basis.

离开 RequestContext 完全不运行任何上下文处理器。

Leave RequestContext out altogether to not run any context processors.

# want context processors listed in settings.py as well as some more specific ones
return render_to_response('template.html', {'foo':'bar'}, context_instance=RequestContext(request, processors = extra_processors))

# want only context processors listed in settings.py
return render_to_response('template.html', {'foo':'bar'}, context_instance=RequestContext(request))

# no context processors
return render_to_response('template.html', {'foo':'bar'})