为了避免耗时和昂贵的精确数据库计数查询,我想在Django管理员类中覆盖
count()
方法,如下所示:from django.contrib import admin
from django.db import connection
class CountProxy:
def __call__(self):
# how to access the queryset `query` here?
query = ...
try:
if not query.where:
cursor = connection.cursor()
cursor.execute("SELECT reltuples FROM pg_class WHERE relname = %s", [query.model._meta.db_table])
n = int(cursor.fetchone()[0])
if n >= 1000: return n # exact count for small tables
return object_list.count()
except:
# exception for lists
return len(object_list)
return estimated_count
class MyAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(MyAdmin, self).get_queryset(request)
qs.count = CountProxy()
return qs
但是我不知道如何在我的CountProxy
类中访问原始查询集。有什么想法吗?我知道我可以通过get_changelist
重写整个changelist
视图。但那需要从Django的库中复制很多重复代码。
object_list
在您的解决方案中未定义。return estimated_count
是无法执行的,并且也未定义。 - radtek