How to override queryset count() method in Django's admin list
I could be wrong, but could you pass qs
as an instance attribute for CountProxy
?
class CountProxy:
def __init__(self, query):
self.query = query
def __call__(self):
# you've already had the query here, do something with self.query
class MyAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(MyAdmin, self).get_queryset(request)
qs.count = CountProxy(qs)
return qs
I did something similar before so I can help.
I defined a custom queryset class:
class MyQuerySet(QuerySet):
def count(self):
"""
Override count queries (performed by Django ORM) to display approximate value.
This will speed the admin interface.
"""
if self._result_cache is not None and not self._iter:
return len(self._result_cache)
query = self.query
if not (query.group_by or query.having or query.distinct):
cursor = connections[self.db].cursor()
cursor.execute("SHOW TABLE STATUS LIKE '%s';" % self.model._meta.db_table)
return cursor.fetchall()[0][4]
else:
return self.query.get_count(using=self.db)
Then defined a custom model manager:
class MyManager(models.Manager):
def get_query_set(self):
return MyQuerySet(self.model)
Then used it in my model:
class MyModel(models.Model):
objects = MyManager()