This is an upgrade of snippet [1103](http://www.djangosnippets.org/snippets/1103/).
Exemplary usage:
class Blog(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=50)
blog = models.ForeignKey(Blog)
def __unicode__(self):
return self.title
class Meta:
abstract=True
class Article(Post):
text = models.TextField()
class Link(Post):
url = models.URLField()
blog = Blog(name="Exemplary blog")
blog.save()
Article(title="#1", text="Exemplary article 1", blog=blog).save()
Article(title="#2", text="Exemplary article 2", blog=blog).save()
Link(title="#3", url="http://exemplary.link.com/", blog=blog).save()
qs1 = Article.objects.all()
qs2 = Link.objects.all()
qsseq = QuerySetSequence(qs1, qs2)
# those all work also on IableSequence
len(qsseq)
len(QuerySetSequence(qs2, qs2))
qsseq[len(qs1)].title
# this is QuerySetSequence specific
qsseq.order_by('blog.name','-title')
excluded_homo = qsseq.exclude(title__contains="3")
# homogenic results - returns QuerySet
type(excluded_homo)
excluded_hetero = qsseq.exclude(title="#2")
# heterogenic results - returns QuerySetSequence
type(excluded_hetero)
excluded_hetero.exists()
You can implement more `QuerySet` API methods if needed. If full API is implemented it makes sense to also subclass the `QuerySet` class.
- queryset
- chain
- iterable
- indexable
I have many heavy views which run slowly when accessed at same time in multiple threads. I make this decorator to allow run only one view at the time and cache returned result. Other threads will wait to complete first thread and use response from the cache if executed thread put it to cache.
Also I take idea of MintCache to refresh staled cache and return cached (stale) response while response refreshed in the cache.
Usage:
@single_cacheable(cache_timeout=60,
stale_timeout=30,
key_template='my_heavy_view-{arg1}-{arg2}')
def heavy_view(request, arg1, arg2):
response = HttpResponse()
... your code here
# cache timeout may be set from inside of view
response._cache_timeout = cache_time
return responce
The "key_template" is a template for cache key. Some my views have additinal parameter "cache_time" which set from parent page and request.path is different for these pages but they need to be cached not depending of this parameter.
Variable "key_template" in the example used named agrument, if you have no named paramaters you need to use 'my_heavy_view-{1}-{2}-{...}' where {1},{2}, {...} arguments of view.
The line with setting "key" variable may be changed to:
key = "sc_"+request.get_full_path()
if you need to take full URL path as cache key.