From 4a8ac71f9d7cc43024867dea5157205260689b49 Mon Sep 17 00:00:00 2001
From: Jonathan Weth <git@jonathanweth.de>
Date: Tue, 29 Dec 2020 17:21:54 +0100
Subject: [PATCH] Make prev/next functions independent of the lesson object/the
 validity range

---
 aleksis/apps/chronos/models.py | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)

diff --git a/aleksis/apps/chronos/models.py b/aleksis/apps/chronos/models.py
index a810fc9b..9b27fa0e 100644
--- a/aleksis/apps/chronos/models.py
+++ b/aleksis/apps/chronos/models.py
@@ -468,6 +468,20 @@ class LessonPeriod(ExtensibleModel, WeekAnnotationMixin):
     def __str__(self) -> str:
         return f"{self.period}, {self.lesson}"
 
+    @property
+    def _equal_lessons(self):
+        """Get all lesson periods with equal lessons in the whole school term."""
+
+        qs = LessonPeriod.objects.filter(
+            lesson__subject=self.lesson.subject,
+            lesson__validity__school_term=self.lesson.validity.school_term,
+        )
+        for group in self.lesson.groups.all():
+            qs = qs.filter(lesson__groups=group)
+        for teacher in self.lesson.teachers.all():
+            qs = qs.filter(lesson__teachers=teacher)
+        return qs
+
     @property
     def next(self) -> "LessonPeriod":
         """Get next lesson period of this lesson.
@@ -475,7 +489,7 @@ class LessonPeriod(ExtensibleModel, WeekAnnotationMixin):
         .. warning::
             To use this property,  the provided lesson period must be annotated with a week.
         """
-        return LessonPeriod.objects.filter(lesson=self.lesson).next_lesson(self)
+        return self._equal_lessons.next_lesson(self)
 
     @property
     def prev(self) -> "LessonPeriod":
@@ -484,7 +498,7 @@ class LessonPeriod(ExtensibleModel, WeekAnnotationMixin):
         .. warning::
             To use this property,  the provided lesson period must be annotated with a week.
         """
-        return LessonPeriod.objects.filter(lesson=self.lesson).next_lesson(self, -1)
+        return self._equal_lessons.next_lesson(self, -1)
 
     class Meta:
         ordering = [
-- 
GitLab