Created
January 13, 2016 12:27
-
-
Save yprez/3c837331eb54cd52f584 to your computer and use it in GitHub Desktop.
Django - EstimateCountManager (faster, but innacurate counts for PostgreSQL)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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