Skip to content

Instantly share code, notes, and snippets.

View goutomroy's full-sized avatar

Goutom Roy goutomroy

View GitHub Profile
# The `if` statement evaluates the queryset and saves results in cache.
queryset = Entry.objects.all()
if queryset:
# Using cache from previous if statement evaluation.
for each in queryset:
print(each.headline)
# Evaluates the queryset and saves results in cache.
queryset = Entry.objects.all()
lst = list(queryset)
# Using cache from previous list() evaluation.
for each in queryset:
print(each.headline)
# len() evaluates and saves results to cache.
queryset = Entry.objects.all()
ln = len(queryset)
# Using cache from previous evaluation.
for each in queryset:
print(each.headline)
# repr() evaluates but does not saves results to cache.
queryset = Entry.objects.all()
str_repr = repr(queryset)
# Not using cache.Hitting database again.
for each in queryset:
print(each.headline)
entry_list = Entry.objects.all()[1:100:2]
queryset = Entry.objects.all()
# Queries the database because queryset hasn't been evaluated yet.
print(queryset[5])
# Queries the database because queryset hasn't been evaluated yet.
print(queryset[5])
lst = list(queryset)
# Using caches because evaluation happened in previous list().
print(queryset[5])
print(queryset[10])
queryset = Entry.objects.all()
lst = list(queryset)
# returns a list of entry objects
first_ten = queryset[:10]
# list slicing not queryset slicing because first_ten is a list.
first_five = first_ten[:5]
# You can't use filter to queryset anymore.
queryset = Entry.objects.all()[10:100]
# You can use filter to q1 but not to q2, q3.
q1 = Entry.objects.all()
q2 = q1[1:10]
q3 = q2[1:5]
# saves results to cache of q1
lst1 = [each.blog.id for each in q1]
queryset = Entry.objects.all()
# Evaluated and cached
for each in queryset:
print(each.headline)
# Using cache from previous evaluation.
for each in queryset:
print(each.headline)
# The following will create two QuerySet's, evaluate them, and throw them away
# because they are not saving the queryset anywhere to reuse them later.
print([e.headline for e in Entry.objects.all()])
print([e.pub_date for e in Entry.objects.all()])
# Following code saves QuerySet in a variable. When it evaluates,
# it saves the results to its cache(_result_cache).
queryset = Entry.objects.all()
# evaluation with iteration.