Quietly building the future.
2016-04-28T21:32:00-07:00
In Django terms, a QuerySet is an iterable of database records. What's nice about them is that they are evaluated only when you're ready for the results.
This means that even if it takes you a few lines of code to chain multiple queries, the Django ORM combines them into a single query. Less queries mean your database doesn't have to work as hard, and your website runs faster.
>>> results = Promo.objects.active()>>> results [<Promo: Free Flavors on Your Birthday>, <Promo: 10% Off All Cones>, <Promo: Buy 1, Get 1 Free>]
>>> results = results.filter( >>> Q(name__istartswith='free') | >>> Q(description__icontains='free') >>> )
>>> results [<Promo: Free Flavors on Your Birthday>]
from django.db import connection>>> connection.queries [ {'sql': 'SELECT "flavors_promo"."id", "flavors_promo"."name", "flavors_promo"."description", "flavors_promo"."status" FROM "flavors_promo" WHERE "flavors_promo"."status" = <span style="color: #e6db74;">'active' LIMIT 21', 'time': '0.000'}, {'sql': 'SELECT "flavors_promo"."id", "flavors_promo"."name", "flavors_promo"."description", "flavors_promo"."status" FROM "flavors_promo" WHERE ("flavors_promo"."status" = <span style="color: #e6db74;">'active' AND ("flavors_promo"."name" LIKE <span style="color: #e6db74;">'free%' ESCAPE '\' OR "flavors_promo"."description" LIKE <span style="color: #e6db74;">'%free%' ESCAPE '\')) LIMIT 21', 'time': '0.001'}]
>>> from django.db import reset_queries >>> reset_queries()
>>> results = Promo.objects.active()>>> results = results.filter( ... Q(name__istartswith=name) | ... Q(description__icontains=name) ... )
>>> results = results.exclude(status='melted')
>>> results [<Promo: Free Flavors on Your Birthday>]
>>> connection.queries [{'sql': 'SELECT "flavors_promo"."id", "flavors_promo"."name", "flavors_promo"."description", "flavors_promo"."status" FROM "flavors_promo" WHERE ("flavors_promo"."status" = \'active\' AND ("flavors_promo"."name" LIKE \'free%\' ESCAPE \'\\\' OR "flavors_promo"."description" LIKE \'%free%\' ESCAPE \'\\\') AND NOT ("flavors_promo"."status" = \'melted\')) LIMIT 21', 'time': '0.001'}]