1
0
Fork 0
mirror of https://github.com/seanmorley15/AdventureLog.git synced 2025-07-24 15:29:36 +02:00

Region check - api

This commit is contained in:
Sean Morley 2024-08-23 18:34:11 -04:00
parent afe83bb03e
commit c13d6f4f21

View file

@ -13,6 +13,7 @@ from django.contrib.gis.geos import Point
from django.conf import settings
from rest_framework.decorators import action
from django.contrib.staticfiles import finders
from adventures.models import Adventure
@api_view(['GET'])
@permission_classes([IsAuthenticated])
@ -49,6 +50,26 @@ class CountryViewSet(viewsets.ReadOnlyModelViewSet):
return Response({'in_region': True, 'region_name': region.name, 'region_id': region.id})
else:
return Response({'in_region': False})
# make a post action that will get all of the users adventures and check if the point is in any of the regions if so make a visited region object for that user if it does not already exist
@action(detail=False, methods=['post'])
def region_check_all_adventures(self, request):
adventures = Adventure.objects.filter(user_id=request.user.id)
count = 0
for adventure in adventures:
if adventure.latitude is not None and adventure.longitude is not None:
try:
print(f"Adventure {adventure.id}: lat={adventure.latitude}, lon={adventure.longitude}")
point = Point(float(adventure.longitude), float(adventure.latitude), srid=4326)
region = Region.objects.filter(geometry__contains=point).first()
if region:
if not VisitedRegion.objects.filter(user_id=request.user.id, region=region).exists():
VisitedRegion.objects.create(user_id=request.user, region=region)
count += 1
except Exception as e:
print(f"Error processing adventure {adventure.id}: {e}")
continue
return Response({'regions_visited': count})
class RegionViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Region.objects.all()