Speed up the address admin list and add subject and type filters.

Skip the full-table count, page with previous and next, and look up filters without scanning every row. Hide Groups from the admin index.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ilya Mukhortov 2026-09-30 09:48:38 +10:00
parent c503f9effb
commit aa1a484531
5 changed files with 393 additions and 21 deletions

View File

@ -1,26 +1,76 @@
from django.contrib import admin from django.contrib import admin
from django.contrib.admin.views.main import PAGE_VAR, ChangeList
from django.contrib.auth.models import Group
from django.core.paginator import Paginator
from django.db.models import Count from django.db.models import Count
from django.urls import reverse from django.urls import reverse
from django.utils.functional import cached_property
from django.utils.html import format_html from django.utils.html import format_html
from .models import AddressObject, House from .models import AddressObject, House
from .object_types import ADDRESS_OBJECT_TYPE_SHORT_NAMES
from django.core.paginator import Paginator class NoCountPaginator(Paginator):
from django.db import connection """Page through a queryset with LIMIT, without COUNT(*)."""
from django.utils.functional import cached_property
def __init__(
self,
object_list,
per_page,
orphans=0,
allow_empty_first_page=True,
page_number=1,
):
self.page_number = page_number if page_number >= 1 else 1
super().__init__(object_list, per_page, orphans, allow_empty_first_page)
class PostgresEstimatedPaginator(Paginator):
@cached_property @cached_property
def count(self): def count(self):
with connection.cursor() as cursor: start = (self.page_number - 1) * self.per_page
# Query the internal Postgres table statistics self._page_objects = list(self.object_list[start : start + self.per_page + 1])
cursor.execute( return start + len(self._page_objects)
"SELECT reltuples FROM pg_class WHERE relname = %s",
[self.object_list.model._meta.db_table] def page(self, number):
number = self.validate_number(number)
return self._get_page(self._page_objects[: self.per_page], number, self)
class RegionCodeFilter(admin.SimpleListFilter):
title = "Субъект РФ"
parameter_name = "region_code"
template = "admin/autocomplete_filter.html"
def lookups(self, request, model_admin):
regions = AddressObject.objects.filter(level=AddressObject.Level.REGION).only(
"name", "type_name", "region_code"
) )
row = cursor.fetchone() by_code = {}
return int(row[0]) if row else 0 for region in regions:
by_code[region.region_code] = f"{region.label} ({region.region_code})"
return sorted(by_code.items(), key=lambda item: item[1])
def queryset(self, request, queryset):
value = self.value()
if value and value.isdigit():
return queryset.filter(region_code=int(value))
return queryset
class TypeNameFilter(admin.SimpleListFilter):
title = "Тип"
parameter_name = "type_name"
template = "admin/autocomplete_filter.html"
def lookups(self, request, model_admin):
names = sorted(set(ADDRESS_OBJECT_TYPE_SHORT_NAMES.values()))
return [(name, name) for name in names]
def queryset(self, request, queryset):
value = self.value()
if value:
return queryset.filter(type_name=value)
return queryset
class ParentIdFilter(admin.SimpleListFilter): class ParentIdFilter(admin.SimpleListFilter):
@ -46,6 +96,44 @@ def children_filter_url(model_name: str, parent_id: int) -> str:
return f"{reverse(f'admin:address_{model_name}_changelist')}?parent={parent_id}" return f"{reverse(f'admin:address_{model_name}_changelist')}?parent={parent_id}"
def attach_child_counts(objects):
ids = [obj.pk for obj in objects if obj.pk is not None]
if not ids:
return
child_counts = dict(
AddressObject.objects.filter(parent_id__in=ids)
.values("parent_id")
.annotate(total=Count("pk"))
.values_list("parent_id", "total")
)
house_counts = dict(
House.objects.filter(parent_id__in=ids)
.values("parent_id")
.annotate(total=Count("pk"))
.values_list("parent_id", "total")
)
for obj in objects:
obj.children_count = child_counts.get(obj.pk, 0)
obj.houses_count = house_counts.get(obj.pk, 0)
class AddressChangeList(ChangeList):
def get_results(self, request):
super().get_results(request)
self.full_result_count = self.result_count
objects = list(self.result_list)
attach_child_counts(objects)
self.result_list = objects
self.previous_page_url = (
self.get_query_string({PAGE_VAR: self.page_num - 1}) if self.page_num > 1 else ""
)
self.next_page_url = (
self.get_query_string({PAGE_VAR: self.page_num + 1})
if self.paginator.num_pages > self.page_num
else ""
)
@admin.register(AddressObject) @admin.register(AddressObject)
class AddressObjectAdmin(admin.ModelAdmin): class AddressObjectAdmin(admin.ModelAdmin):
list_display = ( list_display = (
@ -58,23 +146,36 @@ class AddressObjectAdmin(admin.ModelAdmin):
"kladr_id", "kladr_id",
"is_active", "is_active",
) )
list_filter = ("level", "region_code", "is_active", ParentIdFilter) list_filter = ("level", RegionCodeFilter, TypeNameFilter, "is_active", ParentIdFilter)
search_fields = ("name", "fias_id", "object_id", "kladr_id") search_fields = ("name", "fias_id", "object_id", "kladr_id")
raw_id_fields = ("parent",) raw_id_fields = ("parent",)
readonly_fields = ("children_link",) readonly_fields = ("children_link",)
show_full_result_count = False show_full_result_count = False
hide_result_count = True
list_max_show_all = 0
def get_queryset(self, request): def get_changelist(self, request):
queryset = super().get_queryset(request) return AddressChangeList
return queryset.annotate(
children_count=Count("children", distinct=True), def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True):
houses_count=Count("houses", distinct=True), try:
page_number = int(request.GET.get(PAGE_VAR, 1))
except (TypeError, ValueError):
page_number = 1
return NoCountPaginator(
queryset,
per_page,
orphans,
allow_empty_first_page,
page_number=page_number,
) )
@admin.display(description="Дочерние") @admin.display(description="Дочерние")
def children_link(self, obj: AddressObject): def children_link(self, obj: AddressObject):
if obj.pk is None: if obj.pk is None:
return "—" return "—"
if not hasattr(obj, "children_count"):
attach_child_counts([obj])
children_count = getattr(obj, "children_count", None) children_count = getattr(obj, "children_count", None)
houses_count = getattr(obj, "houses_count", None) houses_count = getattr(obj, "houses_count", None)
links = [] links = []
@ -96,6 +197,9 @@ class AddressObjectAdmin(admin.ModelAdmin):
@admin.register(House) @admin.register(House)
class HouseAdmin(admin.ModelAdmin): class HouseAdmin(admin.ModelAdmin):
list_display = ("display_number", "region_code", "parent", "postal_code") list_display = ("display_number", "region_code", "parent", "postal_code")
list_filter = ("region_code", "house_type", ParentIdFilter) list_filter = (RegionCodeFilter, "house_type", ParentIdFilter)
search_fields = ("house_number", "additional_number_1", "fias_id", "object_id") search_fields = ("house_number", "additional_number_1", "fias_id", "object_id")
raw_id_fields = ("parent",) raw_id_fields = ("parent",)
admin.site.unregister(Group)

View File

@ -57,7 +57,7 @@ ASGI_APPLICATION = "address.asgi.application"
TEMPLATES = [ TEMPLATES = [
{ {
"BACKEND": "django.template.backends.django.DjangoTemplates", "BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [], "DIRS": [BASE_DIR / "address" / "templates"],
"APP_DIRS": True, "APP_DIRS": True,
"OPTIONS": { "OPTIONS": {
"context_processors": [ "context_processors": [

View File

@ -0,0 +1,61 @@
{% load i18n static %}
<details data-filter-title="{{ title }}" open>
<summary>
{% blocktranslate with filter_title=title %} By {{ filter_title }} {% endblocktranslate %}
</summary>
<ul>
<li>
{% with reset=choices.0 %}
<select class="admin-filter-autocomplete">
{% for choice in choices %}
<option value="{{ choice.query_string|iriencode }}"{% if choice.selected %} selected{% endif %}>{{ choice.display }}</option>
{% endfor %}
</select>
{% if not reset.selected %}
<a class="admin-filter-reset" href="{{ reset.query_string|iriencode }}">Сбросить</a>
{% endif %}
{% endwith %}
</li>
</ul>
<link rel="stylesheet" href="{% static 'admin/css/vendor/select2/select2.css' %}">
<link rel="stylesheet" href="{% static 'admin/css/autocomplete.css' %}">
<style>
#changelist-filter .select2-container {
width: 100% !important;
max-width: 100%;
}
#changelist-filter a.admin-filter-reset {
margin-top: 8px;
padding: 4px 8px;
text-align: center;
border: 1px solid var(--border-color);
border-radius: 4px;
background: var(--body-bg);
color: var(--body-fg);
text-decoration: none;
}
</style>
<script>
window.jQuery = window.django.jQuery;
</script>
<script src="{% static 'admin/js/vendor/select2/select2.full.js' %}"></script>
<script src="{% static 'admin/js/vendor/select2/i18n/ru.js' %}"></script>
<script>
django.jQuery(function ($) {
$("#changelist-filter select.admin-filter-autocomplete").each(function () {
const select = $(this);
if (select.data("select2")) {
return;
}
select.select2({
width: "100%",
theme: "admin-autocomplete",
language: "ru",
});
select.on("select2:select", function () {
window.location.href = this.value;
});
});
});
</script>
</details>

View File

@ -0,0 +1,36 @@
{% load admin_list %}
{% load i18n %}
<p class="paginator">
{% if cl.model_admin.hide_result_count %}
{% if cl.previous_page_url %}
<a href="{{ cl.previous_page_url }}">Предыдущая страница</a>
{% else %}
<span class="disabled" aria-disabled="true">Предыдущая страница</span>
{% endif %}
{% if cl.next_page_url %}
<a href="{{ cl.next_page_url }}">Следующая страница</a>
{% else %}
<span class="disabled" aria-disabled="true">Следующая страница</span>
{% endif %}
{% elif pagination_required %}
{% for i in page_range %}
{% paginator_number cl i %}
{% endfor %}
{% endif %}
{% if not cl.model_admin.hide_result_count %}
{{ cl.result_count }} {% if cl.result_count == 1 %}{{ cl.opts.verbose_name }}{% else %}{{ cl.opts.verbose_name_plural }}{% endif %}
{% endif %}
{% if show_all_url %}<a href="{{ show_all_url }}" class="showall">{% translate 'Show all' %}</a>{% endif %}
{% if cl.formset and cl.result_count %}<input type="submit" name="_save" class="default" value="{% translate 'Save' %}">{% endif %}
</p>
<style>
#changelist .paginator .disabled {
display: inline-block;
margin: 0 2px;
padding: 2px 6px;
color: var(--body-quiet-color);
opacity: 0.45;
cursor: default;
pointer-events: none;
}
</style>

View File

@ -2,7 +2,9 @@ import uuid
import pytest import pytest
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.db import connection
from django.test import Client from django.test import Client
from django.test.utils import CaptureQueriesContext
from address.models import AddressObject, House from address.models import AddressObject, House
from address.tests.paths import admin_url from address.tests.paths import admin_url
@ -23,6 +25,8 @@ def test_admin_site_header(admin_client):
html = response.content.decode() html = response.content.decode()
assert "Адресный сервис" in html assert "Адресный сервис" in html
assert "Администрирование Django" not in html assert "Администрирование Django" not in html
assert "auth/group/" not in html
assert "auth/user/" in html
@pytest.mark.django_db @pytest.mark.django_db
@ -51,12 +55,16 @@ def test_address_admin_has_children_filter_link(admin_client):
parent=parent, parent=parent,
) )
with CaptureQueriesContext(connection) as captured:
response = admin_client.get(admin_url("address/addressobject/")) response = admin_client.get(admin_url("address/addressobject/"))
assert response.status_code == 200 assert response.status_code == 200
html = response.content.decode() html = response.content.decode()
assert f"?parent={parent.pk}" in html assert f"?parent={parent.pk}" in html
assert "объекты (1)" in html assert "объекты (1)" in html
assert "дома (1)" in html assert "дома (1)" in html
paginator = html[html.index('<p class="paginator">') : html.index("</p>", html.index('<p class="paginator">'))]
assert "Адресные объекты" not in paginator
assert not any('COUNT(*) AS "__count"' in query["sql"] for query in captured.captured_queries)
response = admin_client.get( response = admin_client.get(
admin_url("address/addressobject/"), {"parent": parent.pk} admin_url("address/addressobject/"), {"parent": parent.pk}
@ -69,3 +77,166 @@ def test_address_admin_has_children_filter_link(admin_client):
response = admin_client.get(admin_url("address/house/"), {"parent": parent.pk}) response = admin_client.get(admin_url("address/house/"), {"parent": parent.pk})
assert response.status_code == 200 assert response.status_code == 200
assert "д. 10" in response.content.decode() assert "д. 10" in response.content.decode()
@pytest.mark.django_db
def test_address_admin_paginates_with_previous_and_next(admin_client, monkeypatch):
from address.admin import AddressObjectAdmin
monkeypatch.setattr(AddressObjectAdmin, "list_per_page", 1)
AddressObject.objects.create(
fias_id=uuid.uuid4(),
name="Арсеньев",
type_name="г",
level=AddressObject.Level.CITY,
region_code=25,
)
AddressObject.objects.create(
fias_id=uuid.uuid4(),
name="Владивосток",
type_name="г",
level=AddressObject.Level.CITY,
region_code=25,
)
response = admin_client.get(admin_url("address/addressobject/"))
html = response.content.decode()
paginator = html[html.index('<p class="paginator">') : html.index("</p>", html.index('<p class="paginator">'))]
assert '<span class="disabled" aria-disabled="true">Предыдущая страница</span>' in paginator
assert "Следующая страница" in paginator
assert "p=2" in paginator
with CaptureQueriesContext(connection) as captured:
response = admin_client.get(admin_url("address/addressobject/"), {"p": "2"})
html = response.content.decode()
paginator = html[html.index('<p class="paginator">') : html.index("</p>", html.index('<p class="paginator">'))]
assert "Предыдущая страница" in paginator
assert '<span class="disabled" aria-disabled="true">Следующая страница</span>' in paginator
assert "Владивосток" in html
assert "Арсеньев" not in html
assert not any('COUNT(*) AS "__count"' in query["sql"] for query in captured.captured_queries)
def _region_filter_html(html: str) -> str:
marker = 'data-filter-title="Субъект РФ"'
start = html.index(marker)
start = html.rindex("<details", 0, start)
end = html.index("</details>", start)
return html[start:end]
@pytest.mark.django_db
def test_region_code_filter_autocompletes_by_name(admin_client):
AddressObject.objects.create(
fias_id=uuid.uuid4(),
name="Приморский",
type_name="край",
level=AddressObject.Level.REGION,
region_code=25,
)
primorye = AddressObject.objects.create(
fias_id=uuid.uuid4(),
name="Владивосток",
type_name="г",
level=AddressObject.Level.CITY,
region_code=25,
)
moscow = AddressObject.objects.create(
fias_id=uuid.uuid4(),
name="Москва",
type_name="г",
level=AddressObject.Level.REGION,
region_code=77,
)
House.objects.create(
object_id=501,
fias_id=uuid.uuid4(),
region_code=25,
house_number="10",
house_type=House.Type.HOUSE,
parent=primorye,
)
House.objects.create(
object_id=502,
fias_id=uuid.uuid4(),
region_code=77,
house_number="5",
house_type=House.Type.HOUSE,
parent=moscow,
)
for path in ("address/addressobject/", "address/house/"):
response = admin_client.get(admin_url(path))
assert response.status_code == 200
region_filter = _region_filter_html(response.content.decode())
assert "admin-filter-autocomplete" in region_filter
assert "select2.full.js" in region_filter
assert "Приморский край (25)" in region_filter
assert "г Москва (77)" in region_filter
assert "region_code=25" in region_filter
assert "region_code=77" in region_filter
assert "Владивосток" not in region_filter
assert ">Сбросить</a>" not in region_filter
response = admin_client.get(
admin_url("address/addressobject/"), {"region_code": "25", "q": "влад"}
)
assert response.status_code == 200
html = response.content.decode()
region_filter = _region_filter_html(html)
assert "Приморский край (25)" in region_filter
reset_href = region_filter.split('class="admin-filter-reset" href="', 1)[1].split('"', 1)[0]
assert "region_code" not in reset_href
assert "q=" in reset_href
result_list = html[html.index('id="result_list"') : html.index("</table>", html.index('id="result_list"'))]
assert primorye.name in result_list
assert moscow.name not in result_list
response = admin_client.get(admin_url("address/house/"), {"region_code": "25"})
assert response.status_code == 200
html = response.content.decode()
assert "д. 10" in html
assert "д. 5" not in html
def _type_filter_html(html: str) -> str:
marker = 'data-filter-title="Тип"'
start = html.index(marker)
start = html.rindex("<details", 0, start)
end = html.index("</details>", start)
return html[start:end]
@pytest.mark.django_db
def test_type_name_filter_autocompletes(admin_client):
row = AddressObject.objects.create(
fias_id=uuid.uuid4(),
name="Северный",
type_name="ряд",
level=AddressObject.Level.STREET,
region_code=25,
)
street = AddressObject.objects.create(
fias_id=uuid.uuid4(),
name="Лесная",
type_name="ул",
level=AddressObject.Level.STREET,
region_code=25,
)
response = admin_client.get(admin_url("address/addressobject/"))
assert response.status_code == 200
type_filter = _type_filter_html(response.content.decode())
assert "admin-filter-autocomplete" in type_filter
assert ">ряд</option>" in type_filter
assert ">ул</option>" in type_filter
assert ">Сбросить</a>" not in type_filter
response = admin_client.get(admin_url("address/addressobject/"), {"type_name": "ряд"})
assert response.status_code == 200
html = response.content.decode()
type_filter = _type_filter_html(html)
assert 'class="admin-filter-reset"' in type_filter
result_list = html[html.index('id="result_list"') : html.index("</table>", html.index('id="result_list"'))]
assert row.name in result_list
assert street.name not in result_list