From 447b034d382a63a36a9c6908b31e3b37d45e413c Mon Sep 17 00:00:00 2001 From: Keannu Bernasol Date: Fri, 14 Jul 2023 23:56:24 +0800 Subject: [PATCH] Improved study_groups geofencing in serializer --- stude/study_groups/serializers.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/stude/study_groups/serializers.py b/stude/study_groups/serializers.py index a0203cb..d67fcb1 100644 --- a/stude/study_groups/serializers.py +++ b/stude/study_groups/serializers.py @@ -3,6 +3,7 @@ from .models import StudyGroup, StudyGroupMembership from accounts.models import CustomUser from subjects.models import Subject from drf_extra_fields.geo_fields import PointField +from landmarks.models import Landmark class StudyGroupSerializer(serializers.ModelSerializer): @@ -11,10 +12,28 @@ class StudyGroupSerializer(serializers.ModelSerializer): subject = serializers.SlugRelatedField( many=False, slug_field='name', queryset=Subject.objects.all(), required=True, allow_null=False) location = PointField() + landmark = serializers.SlugRelatedField( + queryset=Landmark.objects.all(), many=False, slug_field='name', required=False, allow_null=True) + + def create(self, validated_data): + user = self.context['request'].user + study_group = StudyGroup.objects.create( + users=[user], defaults=validated_data) + validated_data['location'].read_only = True + return study_group + + def update(self, instance, validated_data): + # Check each landmark to see if our location is within it + for landmark in Landmark.objects.all(): + if landmark.location.contains(validated_data['location']): + validated_data['landmark'] = landmark + break + return super().update(instance, validated_data) class Meta: model = StudyGroup fields = '__all__' + read_only_fields = ['landmark'] class StudyGroupMembershipSerializer(serializers.ModelSerializer):