我有一个简单的功能,可以根据request.user获取一些其他数据:

def getIsland(request):
 try:
  island = Island.objects.get(user=request.user) # Retrieve
 except Island.DoesNotExist:
  island = Island(user=request.user) # Doesn't exist, create default one
  island.save()
 island.update() # Run scheduled tasks
 return island # Return


问题在于该函数在许多不同的地方(中间件,模板,视图ETC)被调用,从而多次执行查询。有什么办法吗?即

def getIsland(request):
    if HasBeenEvaluatedAlreadyOnThisRequest: return cached
    else:
        [...]

最佳答案

快速而肮脏:

def getIsland(request):
    if hasattr(request, "_cached_island"):
        return request._cached_island
    try:
        island = Island.objects.get(user=request.user) # Retrieve
    except Island.DoesNotExist:
        island = Island(user=request.user) # Doesn't exist, create default one
        island.save()
    island.update() # Run scheduled tasks
    request._cached_island = island
    return island # Return

关于python - Django查询集-确保仅检索结果一次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3712697/

10-11 08:03