-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserializers.py
More file actions
519 lines (449 loc) · 15.3 KB
/
serializers.py
File metadata and controls
519 lines (449 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
from textwrap import dedent
from django.contrib.auth import get_user_model
from rest_framework import serializers
from courses.models import (
Attribute,
Course,
Friendship,
Instructor,
Meeting,
NGSSRestriction,
PreNGSSRequirement,
Section,
StatusUpdate,
UserProfile,
)
from plan.management.commands.recommendcourses import cosine_similarity
class MeetingSerializer(serializers.ModelSerializer):
room = serializers.StringRelatedField(
help_text=dedent(
"""
The room in which the meeting is taking place, in the form '{building code} {room number}'.
"""
)
)
class Meta:
model = Meeting
fields = ("day", "start", "end", "room")
class MeetingWithBuildingSerializer(serializers.ModelSerializer):
room = serializers.StringRelatedField(
help_text=dedent(
"""
The room in which the meeting is taking place, in the form '{building code} {room number}'.
"""
)
)
latitude = serializers.SerializerMethodField(
read_only=True,
help_text="Latitude of building.",
)
longitude = serializers.SerializerMethodField(
read_only=True,
help_text="Longitude of building.",
)
@staticmethod
def get_latitude(obj):
if obj.room and obj.room.building:
return obj.room.building.latitude
return None
@staticmethod
def get_longitude(obj):
if obj.room and obj.room.building:
return obj.room.building.longitude
return None
class Meta:
model = Meeting
fields = ("day", "start", "end", "room", "latitude", "longitude")
class SectionIdSerializer(serializers.ModelSerializer):
id = serializers.CharField(source="full_code")
class Meta:
model = Section
fields = [
"id",
"activity",
]
class InstructorSerializer(serializers.ModelSerializer):
class Meta:
model = Instructor
fields = ["id", "name"]
class MiniSectionSerializer(serializers.ModelSerializer):
section_id = serializers.CharField(
source="full_code",
read_only=True,
help_text=dedent(
"""
The dash-separated dept, full-code, and section-code, e.g. `CIS-120-001` for the
001 lecture section of CIS-120.
"""
),
)
instructors = InstructorSerializer(
many=True,
read_only=True,
help_text="A list of the names of the instructors teaching this section.",
)
course_code = serializers.SerializerMethodField(
read_only=True,
help_text=dedent(
"""
The full code of the course this section belongs to, e.g. `CIS-120` for CIS-120-001.
"""
),
)
course_title = serializers.SerializerMethodField(
read_only=True,
help_text=dedent(
"""
The title of the course this section belongs to, e.g.
'Programming Languages and Techniques I' for CIS-120-001.
"""
),
)
@staticmethod
def get_course_code(obj):
return obj.course.full_code
@staticmethod
def get_course_title(obj):
return obj.course.title
class Meta:
model = Section
fields = [
"section_id",
"status",
"activity",
"meeting_times",
"instructors",
"course_code",
"course_title",
"semester",
"registration_volume",
]
read_only_fields = fields
course_quality_help = "The average course quality rating for this section, on a scale of 0-4."
difficulty_help = "The average difficult rating for this section, on a scale of 0-4."
instructor_quality_help = "The average instructor quality for this section, on a scale of 0-4."
work_required_help = "The average work required for this section, on a scale of 0-4."
class SectionDetailSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField(
source="full_code",
help_text=dedent(
"""
The dash-separated dept, full-code, and section-code, e.g. `CIS-120-001` for the
001 lecture section of CIS-120.
"""
),
)
meetings = serializers.SerializerMethodField(
read_only=True,
help_text=dedent(
"""
A list of the meetings of this section (each meeting is a continuous span of time
during which a section would meet).
"""
),
)
instructors = InstructorSerializer(
read_only=True,
many=True,
help_text="A list of the names of the instructors teaching this section.",
)
associated_sections = SectionIdSerializer(
many=True,
read_only=True,
help_text=dedent(
"""
A list of all sections associated with the Course which this section belongs to; e.g. for
CIS-120-001, all of the lecture and recitation sections for CIS-120 (including CIS-120-001)
in the same semester.
"""
),
)
course_quality = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=course_quality_help
)
difficulty = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=difficulty_help
)
instructor_quality = serializers.DecimalField(
max_digits=4,
decimal_places=3,
read_only=True,
help_text=instructor_quality_help,
)
work_required = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=work_required_help
)
class Meta:
model = Section
fields = [
"id",
"status",
"activity",
"credits",
"capacity",
"semester",
"meetings",
"instructors",
"course_quality",
"instructor_quality",
"difficulty",
"work_required",
"associated_sections",
"registration_volume",
]
read_only_fields = fields
def get_meetings(self, obj):
include_location = self.context.get("include_location", False)
if include_location:
meetings_serializer = MeetingWithBuildingSerializer(obj.meetings, many=True)
else:
meetings_serializer = MeetingSerializer(obj.meetings, many=True)
return meetings_serializer.data
class PreNGSSRequirementListSerializer(serializers.ModelSerializer):
id = serializers.SerializerMethodField(
read_only=True,
help_text="A string representation of the requirement, in the form '{code}@{school}'",
)
@staticmethod
def get_id(obj):
return f"{obj.code}@{obj.school}"
class Meta:
model = PreNGSSRequirement
fields = ["id", "code", "school", "semester", "name"]
read_only_fields = fields
class AttributeListSerializer(serializers.ModelSerializer):
class Meta:
model = Attribute
fields = ["code", "school", "description"]
read_only_fields = fields
class NGSSRestrictionListSerializer(serializers.ModelSerializer):
class Meta:
model = NGSSRestriction
fields = ["code", "restriction_type", "inclusive", "description"]
read_only_fields = fields
class CourseListSerializer(serializers.ModelSerializer):
id = serializers.ReadOnlyField(
source="full_code",
help_text=dedent(
"""
The full code of the course, in the form '{dept code}-{course code}'
dash-joined department and code of the course, e.g. `CIS-120` for CIS-120."""
),
)
num_sections = type(
"SerializerIntMethodField",
(serializers.SerializerMethodField, serializers.IntegerField),
dict(),
)(read_only=True, help_text="The number of sections for this course.")
recommendation_score = type(
"SerializerDecimalMethodField",
(serializers.SerializerMethodField, serializers.DecimalField),
dict(),
)(
read_only=True,
help_text=dedent(
"""
The recommendation score for this course if the user is logged in, or null if the
the user is not logged in."""
),
max_digits=4,
decimal_places=3,
)
def get_num_sections(self, obj):
return obj.sections.count()
def get_recommendation_score(self, obj):
user_vector = self.context.get("user_vector")
curr_course_vectors_dict = self.context.get("curr_course_vectors_dict")
if user_vector is None or curr_course_vectors_dict is None:
# NOTE: there should be no case in which user_vector is None
# but curr_course_vectors_dict is not None. However, for
# stability in production, recommendation_score is None when
# either is None
return None
course_vector = curr_course_vectors_dict.get(obj.full_code)
if course_vector is None:
# Fires when the curr_course_vectors_dict is defined (ie, the user is authenticated)
# but the course code is not in the model
return None
return cosine_similarity(course_vector, user_vector)
course_quality = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=course_quality_help
)
difficulty = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=difficulty_help
)
instructor_quality = serializers.DecimalField(
max_digits=4,
decimal_places=3,
read_only=True,
help_text=instructor_quality_help,
)
work_required = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=work_required_help
)
class Meta:
model = Course
fields = [
"id",
"title",
"description",
"semester",
"num_sections",
"course_quality",
"instructor_quality",
"difficulty",
"work_required",
"recommendation_score",
"credits",
]
read_only_fields = fields
class CourseDetailSerializer(CourseListSerializer):
crosslistings = serializers.SlugRelatedField(
slug_field="full_code",
many=True,
read_only=True,
help_text=dedent(
"""
A list of the full codes (DEPT-###) of all crosslistings for this course
(not including this course).
"""
),
)
sections = SectionDetailSerializer(
many=True, read_only=True, help_text="A list of the sections of this course."
)
pre_ngss_requirements = PreNGSSRequirementListSerializer(
many=True,
read_only=True,
help_text=dedent(
"""
A list of the pre-NGSS (deprecated since 2022B) academic requirements
this course fulfills.
"""
),
)
attributes = AttributeListSerializer(
many=True,
read_only=True,
help_text=dedent(
"""
A list of attributes this course has. Attributes are typically
used to mark courses which students in a program/major should
take.
"""
),
)
restrictions = NGSSRestrictionListSerializer(
many=True,
read_only=True,
help_text=dedent(
"""
A list of NGSSRestrictions this course has. Restrictions provide information about
who can take a course.
"""
),
)
course_quality = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=course_quality_help
)
difficulty = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=difficulty_help
)
instructor_quality = serializers.DecimalField(
max_digits=4,
decimal_places=3,
read_only=True,
help_text=instructor_quality_help,
)
work_required = serializers.DecimalField(
max_digits=4, decimal_places=3, read_only=True, help_text=work_required_help
)
class Meta:
model = Course
fields = [
"id",
"title",
"description",
"syllabus_url",
"semester",
"prerequisites",
"course_quality",
"instructor_quality",
"difficulty",
"work_required",
"credits",
] + [
"crosslistings",
"pre_ngss_requirements",
"attributes",
"restrictions",
"sections",
]
read_only_fields = fields
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ["email", "phone", "push_notifications", "has_been_onboarded"]
class UserSerializer(serializers.ModelSerializer):
profile = UserProfileSerializer(
read_only=False,
help_text="The user profile object, storing collected info about the user.",
required=False,
)
def update(self, instance, validated_data):
prof, _ = UserProfile.objects.get_or_create(user=instance)
prof_data = validated_data.get("profile", None)
for key in ["first_name", "last_name"]:
if key in validated_data:
setattr(instance, key, validated_data[key])
if prof_data is not None:
for key in ["phone", "email", "push_notifications", "has_been_onboarded"]:
if key in prof_data:
setattr(prof, key, prof_data[key])
prof.save()
setattr(instance, "profile", prof)
instance.save()
return instance
class Meta:
model = get_user_model()
fields = ["username", "first_name", "last_name", "profile"]
read_only_fields = ["username"]
class PublicUserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ["username", "first_name", "last_name"]
read_only_fields = ["username"]
class StatusUpdateSerializer(serializers.ModelSerializer):
section = serializers.ReadOnlyField(
source="section__full_code",
read_only=True,
help_text=dedent(
"""
The code of the section which this status update applies to, in the form
'{dept code}-{course code}-{section code}', e.g. `CIS-120-001` for the
001 section of CIS-120.
"""
),
)
class Meta:
model = StatusUpdate
fields = ["section", "old_status", "new_status", "created_at", "alert_sent"]
read_only_fields = fields
class FriendshipSerializer(serializers.ModelSerializer):
class Meta:
model = Friendship
fields = ["sender", "recipient", "status", "sent_at", "accepted_at"]
sender = PublicUserSerializer(
read_only=True,
help_text="The user that is sending the request.",
required=False,
)
recipient = PublicUserSerializer(
read_only=True,
help_text="The user that is recieving the request.",
required=False,
)
class FriendshipRequestSerializer(serializers.Serializer):
friend_id = serializers.IntegerField()
def to_representation(self, instance):
return super().to_representation(instance)