gpt4 book ai didi

python - 是否可以检查自定义上下文处理器定义中的 View 中是否已设置上下文变量?

转载 作者:行者123 更新时间:2023-11-28 19:27:38 25 4
gpt4 key购买 nike

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

感谢您的任何建议!

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)}

最佳答案

def always_G(request):
if not hasattr(request, 'G'):
{'G':G.objects.get(user=request.user)}

关于python - 是否可以检查自定义上下文处理器定义中的 View 中是否已设置上下文变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5996680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com