是否可以检查自定义上下文处理器定义中的视图中是否已经设置了上下文变量? [英] Is it possible to check whether a context variable is already set in a view within a custom context processor definition?

查看:39
本文介绍了是否可以检查自定义上下文处理器定义中的视图中是否已经设置了上下文变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题在于,在某些视图中,由于要使用该上下文变量来查找该特定视图(即视图A,B,C)中的其他信息,因此我会手动获取感兴趣的上下文变量(假设为"G"),但是在其他视图(即X,Y,Z)中,我需要获取特定的上下文变量,因为该上下文在我项目的每个视图中都可用(因为我的基本模板使用了上下文变量).使用自定义上下文处理器的问题在于,我认为它将在视图(A,B,C)中进行额外的IDENTICAL DB调用,因为这些视图已经获取了该上下文变量,因为需要在视图中获取其他数据.我当时在想,也许我可以实现一个上下文处理器,以检查是否为给定请求设置了特定的上下文变量.这可能吗?有没有更简单的解决方案?下面的代码可能会为某些人澄清这个问题.

The issue is that in some views, I am manually getting a context variable (let's say "G") of interest since I use it to find other information in that particular view (i.e.views A,B,C), but in other views (i.e. X,Y,Z), I need to get that particular context variable since this context is to be available in every single view in my project (since my base template uses the context variable). The issue with using a custom context processor is that I believe it will make an additional and IDENTICAL DB call in views (A,B,C) since those views are already getting that context variable since it's needed to get other data in the view. What I was thinking was maybe I could implement a context processor that checks whether that specific context variable is set for a given request. Is this possible? Is there an easier solution? The code below may clarify the issue for some people.

谢谢您的任何建议!

def viewA(request):
    g=G.objects.get(user=request.user)
    posts = Post.objects.filter(g=g)
    return direct_to_template(request,'something.html',{'G':g, 'posts':posts})

def viewX(request):
    stuff = Albums.objects.get(user=request.user)
    return direct_to_template(request,'something2.html',{'stuff':stuff})

def my_context_processor(request): #redundant in case of viewA (hits db again?)
    return {'G':G.objects.get(user=request.user)} 

def ideal_processor(request):
    #check context vars to see if G is already in there
    #if it is, return {}, else, return {'G':G.objects.get(user=request.user)} 

推荐答案

我刚刚制作了将variabel G设置为request.G的中间件,因为无论如何我几乎在每个请求上都需要它.即:

I just made middleware that sets the variabel G to request.G since I need it on virtually every request anyway. i.e.:

class GuildMiddleware(object):
    def process_request(self, request):
        request.G = figure_out_what_G_is()
        return None

现在,您可以在视图的任何位置(如果使用direct_to_template,RequestContext等,则可以使用模板)使用request.G.

Now you can use request.G anywhere in your views (and templates if you're using direct_to_template, RequestContext, etc.).

这篇关于是否可以检查自定义上下文处理器定义中的视图中是否已经设置了上下文变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆