Fixed ExtentForLocation API issue

This commit is contained in:
2025-08-31 17:35:06 +09:00
parent 104d39a96b
commit 77acb7c016
2 changed files with 133 additions and 3 deletions

View File

@ -729,14 +729,29 @@ def ExtentForLocations(request):
return JsonResponse({"error": "No event code associated with the user"}, status=status.HTTP_400_BAD_REQUEST) return JsonResponse({"error": "No event code associated with the user"}, status=status.HTTP_400_BAD_REQUEST)
try: try:
locs = Location2025.objects.filter(group__contains=ec).aggregate(Extent('geom'), Union('geom')) # event_codeに基づいてイベントを検索し、そのイベントに関連するLocation2025を取得
from rog.models import NewEvent2
from django.db.models import Q
# event_codeでイベントを検索event_nameに含まれる場合も考慮
events = NewEvent2.objects.filter(
Q(event_code=ec) |
Q(event_name__icontains=ec)
)
if not events.exists():
logger.warning(f"No events found for event_code: {ec}")
return JsonResponse({"error": "No events found for the given event code"}, status=status.HTTP_404_NOT_FOUND)
# 見つかったイベントに関連するLocation2025を取得
locs = Location2025.objects.filter(event__in=events).aggregate(Extent('location'), Union('location'))
if not locs['geom__extent']: if not locs['location__extent']:
logger.info(f"No locations found for event_code: {ec}") logger.info(f"No locations found for event_code: {ec}")
return JsonResponse({"error": "No locations found for the given event code"}, status=status.HTTP_404_NOT_FOUND) return JsonResponse({"error": "No locations found for the given event code"}, status=status.HTTP_404_NOT_FOUND)
logger.info(f"Successfully retrieved extent for event_code: {ec}") logger.info(f"Successfully retrieved extent for event_code: {ec}")
return JsonResponse(locs['geom__extent'], safe=False) return JsonResponse(locs['location__extent'], safe=False)
except Exception as e: except Exception as e:
logger.error(f"Error in ExtentForLocations: {str(e)}", exc_info=True) logger.error(f"Error in ExtentForLocations: {str(e)}", exc_info=True)

View File

@ -0,0 +1,115 @@
#!/usr/bin/env python
"""
Location2025テーブルの新しいフィールドを旧Locationテーブルから更新するスクリプト
"""
import os
import sys
import django
# Django設定
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rogaining_srv.settings')
django.setup()
from rog.models import Location2025, Location
from django.db import transaction
def update_location2025_from_old_location():
"""
旧Locationテーブルから Location2025 の新しいフィールドを更新
"""
print("=== Location2025フィールド更新開始 ===")
# 更新対象のフィールドマッピング
field_mapping = {
'category': 'category',
'zip_code': 'zip', # Location2025.zip_code <- Location.zip
'prefecture': 'prefecture',
'area': 'area',
'city': 'city',
'facility': 'facility'
}
updated_count = 0
not_found_count = 0
try:
with transaction.atomic():
location2025_records = Location2025.objects.all()
total_records = location2025_records.count()
print(f"処理対象レコード数: {total_records}")
for i, loc2025 in enumerate(location2025_records, 1):
if i % 100 == 0:
print(f"進行状況: {i}/{total_records}")
# location_idまたはcp_nameで旧Locationテーブルから対応するレコードを検索
old_location = None
# まずlocation_idで検索sub_loc_idがlocation_idの可能性
if loc2025.sub_loc_id:
try:
location_id = int(loc2025.sub_loc_id)
old_location = Location.objects.filter(location_id=location_id).first()
except (ValueError, TypeError):
pass
# location_idで見つからない場合、location_nameで検索
if not old_location:
old_location = Location.objects.filter(location_name=loc2025.cp_name).first()
# 部分一致で検索
if not old_location and loc2025.cp_name:
old_location = Location.objects.filter(location_name__icontains=loc2025.cp_name).first()
if old_location:
# フィールドを更新
updated = False
for loc2025_field, location_field in field_mapping.items():
if hasattr(old_location, location_field):
old_value = getattr(old_location, location_field)
if old_value: # 値が存在する場合のみ更新
# zip_codeの場合、〒記号を除去
if loc2025_field == 'zip_code' and old_value.startswith(''):
old_value = old_value[1:]
setattr(loc2025, loc2025_field, old_value)
updated = True
if updated:
loc2025.save()
updated_count += 1
if i <= 5: # 最初の5件の詳細を表示
print(f" 更新: CP{loc2025.cp_number} {loc2025.cp_name}")
print(f" Category: {loc2025.category}")
print(f" Area: {loc2025.area}, Prefecture: {loc2025.prefecture}")
print(f" City: {loc2025.city}, Zip: {loc2025.zip_code}")
print(f" Facility: {loc2025.facility}")
else:
not_found_count += 1
if not_found_count <= 5: # 最初の5件のエラーを表示
print(f" 見つからない: CP{loc2025.cp_number} {loc2025.cp_name} (sub_loc_id: {loc2025.sub_loc_id})")
print(f"\n=== 更新完了 ===")
print(f"更新されたレコード数: {updated_count}")
print(f"対応するLocationが見つからないレコード数: {not_found_count}")
# 更新結果のサンプルを表示
print(f"\n=== 更新後サンプル ===")
updated_samples = Location2025.objects.exclude(category__isnull=True).exclude(category='')[:3]
for sample in updated_samples:
print(f"CP{sample.cp_number}: {sample.cp_name}")
print(f" Category: {sample.category}")
print(f" Location: {sample.prefecture} {sample.area} {sample.city}")
print(f" Zip: {sample.zip_code}, Facility: {sample.facility}")
print()
except Exception as e:
print(f"エラーが発生しました: {e}")
raise
if __name__ == "__main__":
update_location2025_from_old_location()