Skip to content

Instantly share code, notes, and snippets.

@yprez
Created January 13, 2016 12:27
Show Gist options
  • Save yprez/3c837331eb54cd52f584 to your computer and use it in GitHub Desktop.
Save yprez/3c837331eb54cd52f584 to your computer and use it in GitHub Desktop.
Django - EstimateCountManager (faster, but innacurate counts for PostgreSQL)
from django.db import connection
from django.db import models
class EstimateCountManager(models.Manager):
def estimate_count(self):
"""
Postgres really sucks at full table counts, this is a faster version
see: http://wiki.postgresql.org/wiki/Slow_Counting
"""
table_name = self.model._meta.db_table
cursor = connection.cursor()
cursor.execute("SELECT reltuples FROM pg_class WHERE relname='%s';" % table_name)
row = cursor.fetchone()
return int(row[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment