diff --git a/taiga/projects/notifications/api.py b/taiga/projects/notifications/api.py index b5f1b126..b65956d3 100644 --- a/taiga/projects/notifications/api.py +++ b/taiga/projects/notifications/api.py @@ -44,10 +44,9 @@ class NotifyPolicyViewSet(ModelCrudViewSet): projects = Project.objects.filter( Q(owner=self.request.user) | Q(memberships__user=self.request.user) - ) + ).distinct() for project in projects: - if not services.notify_policy_exists(project, self.request.user): - services.create_notify_policy(project, self.request.user, NotifyLevel.watch) + services.create_notify_policy_if_not_exists(project, self.request.user, NotifyLevel.watch) def get_queryset(self): self._build_needed_notify_policies() @@ -55,5 +54,5 @@ class NotifyPolicyViewSet(ModelCrudViewSet): qs = models.NotifyPolicy.objects.filter( Q(project__owner=self.request.user) | Q(project__memberships__user=self.request.user) - ).order_by("project__name") + ) return qs.distinct() diff --git a/taiga/projects/notifications/services.py b/taiga/projects/notifications/services.py index 90a06049..5ec435ca 100644 --- a/taiga/projects/notifications/services.py +++ b/taiga/projects/notifications/services.py @@ -52,6 +52,20 @@ def create_notify_policy(project, user, level=NotifyLevel.notwatch): raise exc.IntegrityError("Notify exists for specified user and project") from e +def create_notify_policy_if_not_exists(project, user, level=NotifyLevel.notwatch): + """ + Given a project and user, create notification policy for it. + """ + model_cls = get_model("notifications", "NotifyPolicy") + try: + result = model_cls.objects.get_or_create(project=project, + user=user, + defaults={"notify_level": level}) + return result[0] + except IntegrityError as e: + raise exc.IntegrityError("Notify exists for specified user and project") from e + + def get_notify_policy(project, user): """ Get notification level for specified project and user.