代码之家  ›  专栏  ›  技术社区  ›  Robus

Django querysets-确保只检索一次结果

  •  1
  • Robus  · 技术社区  · 15 年前

    我有一个简单的函数来获取一些额外的数据请求用户:

    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
    

    def getIsland(request):
        if HasBeenEvaluatedAlreadyOnThisRequest: return cached
        else:
            [...]
    
    3 回复  |  直到 15 年前
        1
  •  1
  •   Ned Batchelder    15 年前

    又快又脏:

    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
    
        2
  •  2
  •   Swizec Teller    15 年前

    Django有一个很好的缓存系统: http://docs.djangoproject.com/en/dev/topics/cache/

    这会使函数看起来像这样:

    def getIsland(request):
     island = cache.get("island_"+request.user)
     if island == None:
       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
       cache.set("island_"+request.user, island, 60)
     return island # Return
    

        3
  •  0
  •   Mike Axiak    15 年前

    如果您有多个进程正在运行,或者多台计算机正在访问同一个数据库,那么您当然无法减少运行此数据库的查询数。

    您可以尝试使用threadlocal存储来保存用户的全局“缓存”。例如:

    class UserStorage(threading.local):
        store = {}
        def getIsland(self, request):
            user_id = request.user.pk
            island = store.get(user_id)
            if island is None:
                island, created = Island.objects.get_or_create(user = user_id)
                store[user_id] = island
            island.update()
            return island