Skip to content

Instantly share code, notes, and snippets.

View goutomroy's full-sized avatar

Goutom Roy goutomroy

View GitHub Profile
@query_debugger
def store_list():
queryset = Store.objects.all()
stores = []
for store in queryset:
books = [book.name for book in store.books.all()]
stores.append({'id': store.id, 'name': store.name, 'books': books})
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=300)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=300)
from django.db import connection, reset_queries
import time
import functools
def query_debugger(func):
@functools.wraps(func)
def inner_func(*args, **kwargs):
reset_queries()
import random
from django.core.management.base import BaseCommand
from apps.bookstore.models import Publisher, Store, Book
class Command(BaseCommand):
"""
This command is for inserting Publisher, Book, Store into database.
Insert 5 Publishers, 100 Books, 10 Stores.
"""
# 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.
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)
# 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]