Skip to content

Commit 3008885

Browse files
committed
improve sort key function
1 parent 9e097ea commit 3008885

File tree

1 file changed

+39
-5
lines changed

1 file changed

+39
-5
lines changed

backend/answers/models.py

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from django.contrib.postgres.indexes import GinIndex
77
from util.models import CommentMixin
88
from django_prometheus.models import ExportModelOperationsMixin
9+
import datetime
910

1011
import random
1112

@@ -52,17 +53,50 @@ def attachment_name(self):
5253
" ", "_"
5354
)
5455

55-
def sort_key(self):
56-
month_val = next((val for month, val in {"december": 0.4, "august": 0.3, "may": 0.2, "april": 0.1}.items()
57-
if month in self.displayname.lower()), 0)
56+
def sort_key_number(self):
57+
# original sort key function
5858
end = 0
5959
while (
6060
end + 1 < len(self.displayname) and self.displayname[-end - 1 :].isdigit()
6161
):
6262
end += 1
6363
if end == 0:
64-
return month_val, self.displayname
65-
return int(self.displayname[-end:])+month_val, self.displayname
64+
return 0, self.displayname
65+
return int(self.displayname[-end:])
66+
67+
def try_parse_exam_date(self):
68+
exam_name = self.displayname
69+
parts_of_name = exam_name.strip().split()
70+
month = None
71+
year = None
72+
for part in parts_of_name:
73+
try:
74+
month = datetime.datetime.strptime(part, "%B")
75+
except ValueError:
76+
pass
77+
try:
78+
year = datetime.datetime.strptime(part, "%Y")
79+
except ValueError:
80+
pass
81+
if month and year:
82+
break
83+
if not(year):
84+
return datetime.datetime(1984, 1, 1)
85+
# in a one or two courses, there are 'Exams' with no year and no month. this puts them at the end
86+
# i haven't seen an exam with just a month.
87+
if year and month: return datetime.datetime(year.year, month.month, 1)
88+
if year and not(month): return year
89+
90+
def sort_key(self):
91+
if self.exam_type.displayname in ["Exams", "Mock Exams"]:
92+
try:
93+
val = datetime.datetime.strptime(self.displayname.strip(), "%B %Y")
94+
except ValueError:
95+
val = self.try_parse_exam_date()
96+
else:
97+
val = self.sort_key_number()
98+
99+
return val, self.displayname
66100

67101
def count_answered(self):
68102
return self.answersection_set.filter(

0 commit comments

Comments
 (0)