Beispiel #1
0
    def get(self, *args, **kwargs):
        """
        Checks the cache to see if there's a cached entry for this pk. If not, fetches 
        using super then stores the result in cache.

        Most of the logic here was gathered from a careful reading of 
        ``django.db.models.sql.query.add_filter``
        """
        if self.query.where:
            # If there is any other ``where`` filter on this QuerySet just call
            # super. There will be a where clause if this QuerySet has already
            # been filtered/cloned.
            return super(CachingQuerySet, self).get(*args, **kwargs)

        # Punt on anything more complicated than get by pk/id only...
        if len(kwargs) == 1:
            k = kwargs.keys()[0]
            if k in ('pk', 'pk__exact', '%s' % self.model._meta.pk.attname, 
                     '%s__exact' % self.model._meta.pk.attname):
                obj = cache.get(self.model._cache_key(pk=kwargs.values()[0]))
                if obj is not None:
                    obj.from_cache = True
                    return obj
        obj = super(CachingQuerySet, self).get(*args, **kwargs)
        cache.set(obj.cache_key,obj)
        return obj
Beispiel #2
0
 def all(self):
     key = instance._get_cache_key(field=field_name)
     qs = super(CachingRelatedManager, self).get_query_set()
     PKListQuerySet = get_pk_list_query_set(qs.__class__)
     qs = qs._clone(klass=PKListQuerySet)
     pk_list = cache.get(key)
     if pk_list is None:
         pk_list = qs.values_list('pk', flat=True)
         cache.add(key, list(pk_list), CACHE_DURATION)
     else:
         qs.from_cache = True
     qs.pk_list = pk_list
     return qs