Add bulk add functionality for user and CID groups to exam collections

This commit is contained in:
Ross
2025-11-12 21:19:09 +00:00
parent c39d30c746
commit ec0245fe7c
7 changed files with 207 additions and 3 deletions
+86
View File
@@ -1946,6 +1946,92 @@ class ExamCollection(models.Model, AuthorMixin):
exam.add_markers(users)
#return True
def bulk_add_user_user_groups(self, groups, exam_types: None | list[str] = None) -> int:
"""Bulk-add one or more UserUserGroup objects (or PKs) to all exams in this
collection.
Args:
groups: iterable of UserUserGroup instances or an iterable of PKs (ints),
or a Django QuerySet of UserUserGroup.
exam_types: optional list of exam type keys to limit the operation. Keys
are the same as returned by `get_exams()` (e.g. 'physics', 'anatomy').
Returns:
Number of exams that were updated (int).
Note: permission checks are not performed here; callers should ensure the
current user is allowed to modify these exams.
"""
# import locally to avoid circular import surprises when module is imported
UserUserGroup = globals().get("UserUserGroup")
if UserUserGroup is None:
raise RuntimeError("UserUserGroup model not available")
# Normalize groups to a list of model instances
if groups is None:
return 0
# If groups is a queryset or list of model instances, materialize it
try:
# QuerySet-ish
groups_qs = list(groups)
except TypeError:
# single value provided
groups_qs = [groups]
# If provided values were ints (PKs), resolve them to model instances
if groups_qs and all(isinstance(g, int) for g in groups_qs):
groups_qs = list(UserUserGroup.objects.filter(pk__in=groups_qs))
if not groups_qs:
return 0
updated = 0
for exam_type, exams in self.get_exams().items():
if exam_types is not None and exam_type not in exam_types:
continue
for exam in exams:
# Each exam model exposes a `user_user_groups` ManyToManyField
exam.user_user_groups.add(*groups_qs)
updated += 1
return updated
def bulk_add_cid_user_groups(self, groups, exam_types: None | list[str] = None) -> int:
"""Bulk-add one or more CidUserGroup objects (or PKs) to all exams in this
collection. Returns number of exams updated.
"""
CidUserGroup = globals().get("CidUserGroup")
if CidUserGroup is None:
raise RuntimeError("CidUserGroup model not available")
if groups is None:
return 0
try:
groups_qs = list(groups)
except TypeError:
groups_qs = [groups]
if groups_qs and all(isinstance(g, int) for g in groups_qs):
groups_qs = list(CidUserGroup.objects.filter(pk__in=groups_qs))
if not groups_qs:
return 0
updated = 0
for exam_type, exams in self.get_exams().items():
if exam_types is not None and exam_type not in exam_types:
continue
for exam in exams:
# Each exam model exposes a `cid_user_groups` ManyToManyField
exam.cid_user_groups.add(*groups_qs)
updated += 1
return updated
#class Presentation(models.Model, AuthorMixin):
#