fix query

This commit is contained in:
zakhy 2025-07-09 14:35:38 +07:00
parent 75f8866409
commit e9889aa3be

View File

@ -2,7 +2,7 @@ import json
from datetime import timedelta
from django.core.serializers import serialize
from django.db.models import Count, OuterRef, Subquery
from django.db.models import Count, IntegerField, OuterRef, Subquery
from django.http import HttpRequest, JsonResponse
from django.utils import timezone
from django.views import View
@ -62,25 +62,31 @@ class StreetZoneTagsCountApiView(View):
offset = timedelta(days=2)
now = BaseService.get_current_time()
timeout = now - offset
tags_in_zone = Tag.objects.filter(
is_street=True,
geo_point__isnull=False,
geo_point__within=OuterRef("polygon"),
date_time_street__gte=timeout,
)
# Подсчет тегов внутри каждого полигона
zones_with_tag_counts = StreetZone.objects.annotate(
tag_count=Count(Subquery(tags_in_zone.values("id"))),
tag_count=Subquery(
Tag.objects.filter(
is_street=True,
geo_point__isnull=False,
geo_point__within=OuterRef("polygon"),
date_time_street__gte=timeout,
)
.annotate(count=Count("id"))
.values("count")[:1],
output_field=IntegerField(),
)
)
items: list = []
for zone in zones_with_tag_counts:
items.append({"id": zone.id, "count": zone.tag_count})
items = [
{"id": zone.id, "count": zone.tag_count or 0}
for zone in zones_with_tag_counts
]
res = {
"error": "",
"status": 0,
"total": zones_with_tag_counts.count(),
"total": len(items),
"items": items,
}
return JsonResponse(res)