2023-06-27 21:35:19 +08:00
|
|
|
from rest_framework import serializers
|
|
|
|
from .models import StudyGroup, StudyGroupMembership
|
|
|
|
from accounts.models import CustomUser
|
2023-07-06 21:47:28 +08:00
|
|
|
from subjects.models import Subject
|
2023-07-14 23:55:54 +08:00
|
|
|
from drf_extra_fields.geo_fields import PointField
|
2023-07-14 23:56:24 +08:00
|
|
|
from landmarks.models import Landmark
|
2023-06-27 21:35:19 +08:00
|
|
|
|
|
|
|
|
|
|
|
class StudyGroupSerializer(serializers.ModelSerializer):
|
|
|
|
users = serializers.SlugRelatedField(
|
2023-07-06 21:47:28 +08:00
|
|
|
queryset=CustomUser.objects.all(), many=True, slug_field='name', required=False, allow_null=True)
|
|
|
|
subject = serializers.SlugRelatedField(
|
|
|
|
many=False, slug_field='name', queryset=Subject.objects.all(), required=True, allow_null=False)
|
2023-07-14 23:55:54 +08:00
|
|
|
location = PointField()
|
2023-07-14 23:56:24 +08:00
|
|
|
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)
|
2023-06-27 21:35:19 +08:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = StudyGroup
|
|
|
|
fields = '__all__'
|
2023-07-14 23:56:24 +08:00
|
|
|
read_only_fields = ['landmark']
|
2023-06-27 21:35:19 +08:00
|
|
|
|
|
|
|
|
|
|
|
class StudyGroupMembershipSerializer(serializers.ModelSerializer):
|
|
|
|
user = serializers.CharField(source='accounts.CustomUser', read_only=True)
|
|
|
|
subject = serializers.CharField(
|
|
|
|
source='study_groups.StudyGroup', read_only=True)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = StudyGroupMembership
|
|
|
|
fields = '__all__'
|