【发布时间】:2017-01-04 15:42:11
【问题描述】:
为了避免耗时且昂贵的精确数据库计数查询,我想在 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无法访问,因此永远不会执行,而且也未定义。