svleeuwen
4/16/2019 - 11:26 PM

PostgreSQL / Django approximate count


class CustomManager(models.Manager):
    def approximate_count(self):
        with connection.cursor() as cursor:
            cursor.execute(
                "SELECT reltuples FROM pg_class WHERE relname = '[table_name]'"
            )
            row = cursor.fetchone()
        try:
            return int(row[0])
        except TypeError:
            return 0