#Python Gem of the Day
💎: Avoid Counting in Django Pagination by Nik Tomazic: https://testdriven.io/blog/django-avoid-counting/
- Default Django paginator uses SELECT COUNT(*). Slow for big tables.
- Discusses an implementation of paginator class without COUNT.
- Overfetches an object and uses that to determine if next page is present.
𝚍𝚎𝚏 𝚙𝚊𝚐𝚎(𝚜𝚎𝚕𝚏, 𝚗𝚞𝚖𝚋𝚎𝚛):
...
𝚋𝚘𝚝𝚝𝚘𝚖 = (𝚗𝚞𝚖𝚋𝚎𝚛 - 𝟷) * 𝚜𝚎𝚕𝚏.𝚙𝚎𝚛_𝚙𝚊𝚐𝚎
𝚝𝚘𝚙 = 𝚋𝚘𝚝𝚝𝚘𝚖 + 𝚜𝚎𝚕𝚏.𝚙𝚎𝚛_𝚙𝚊𝚐𝚎 + 𝟷
...
- Can also be applied to other ORMS too for optimizing perf.