from django.contrib import admin from django.db.models import Count from django.urls import reverse from django.utils.html import format_html from .models import AddressObject, House from django.core.paginator import Paginator from django.db import connection from django.utils.functional import cached_property class PostgresEstimatedPaginator(Paginator): @cached_property def count(self): with connection.cursor() as cursor: # Query the internal Postgres table statistics cursor.execute( "SELECT reltuples FROM pg_class WHERE relname = %s", [self.object_list.model._meta.db_table] ) row = cursor.fetchone() return int(row[0]) if row else 0 class ParentIdFilter(admin.SimpleListFilter): title = "родитель" parameter_name = "parent" def lookups(self, request, model_admin): parent_id = request.GET.get(self.parameter_name) if not parent_id or not parent_id.isdigit(): return [] parent = AddressObject.objects.filter(pk=parent_id).first() if parent is None: return [] return [(parent.pk, str(parent))] def queryset(self, request, queryset): if self.value(): return queryset.filter(parent_id=self.value()) return queryset def children_filter_url(model_name: str, parent_id: int) -> str: return f"{reverse(f'admin:address_{model_name}_changelist')}?parent={parent_id}" @admin.register(AddressObject) class AddressObjectAdmin(admin.ModelAdmin): list_display = ( "name", "type_name", "level", "region_code", "parent", "children_link", "kladr_id", "is_active", ) list_filter = ("level", "region_code", "is_active", ParentIdFilter) search_fields = ("name", "fias_id", "object_id", "kladr_id") raw_id_fields = ("parent",) readonly_fields = ("children_link",) show_full_result_count = False def get_queryset(self, request): queryset = super().get_queryset(request) return queryset.annotate( children_count=Count("children", distinct=True), houses_count=Count("houses", distinct=True), ) @admin.display(description="Дочерние") def children_link(self, obj: AddressObject): if obj.pk is None: return "—" children_count = getattr(obj, "children_count", None) houses_count = getattr(obj, "houses_count", None) links = [] if children_count != 0: label = "объекты" if children_count is None else f"объекты ({children_count})" links.append( format_html('{}', children_filter_url("addressobject", obj.pk), label) ) if houses_count != 0: label = "дома" if houses_count is None else f"дома ({houses_count})" links.append( format_html('{}', children_filter_url("house", obj.pk), label) ) if not links: return "—" return format_html(" · ".join(["{}"] * len(links)), *links) @admin.register(House) class HouseAdmin(admin.ModelAdmin): list_display = ("display_number", "region_code", "parent", "postal_code") list_filter = ("region_code", "house_type", ParentIdFilter) search_fields = ("house_number", "additional_number_1", "fias_id", "object_id") raw_id_fields = ("parent",)