From bbbe9f3f28c8c94c8e9a9a47c2afb89426ab51b3 Mon Sep 17 00:00:00 2001 From: Joseph Muller Date: Fri, 13 Dec 2024 12:51:28 +0000 Subject: [PATCH] Display primary affiliation; add primary if first #3168 --- src/core/models.py | 15 ++++++++++++++- src/core/tests/test_models.py | 18 ++++++++++++++++++ .../admin/core/affiliation_display.html | 7 ++++++- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/core/models.py b/src/core/models.py index 5dc404f90..d149b21e7 100644 --- a/src/core/models.py +++ b/src/core/models.py @@ -2258,7 +2258,7 @@ class Affiliation(models.Model): ) class Meta: - ordering = ['-pk'] + ordering = ['is_primary', '-pk'] def title_department(self): elements = [ @@ -2284,6 +2284,18 @@ def is_current(self): return False return True + @classmethod + def set_primary_if_first(cls, obj): + other_affiliations = cls.objects.filter( + account=obj.account, + frozen_author=obj.frozen_author, + preprint_author=obj.preprint_author, + ).exclude( + pk=obj.pk + ).exists() + if not other_affiliations: + obj.is_primary = True + @classmethod def keep_is_primary_unique(cls, obj): if obj.is_primary: @@ -2426,6 +2438,7 @@ def naive_set_primary_country( affiliation.organization.locations.add(country_location) def save(self, *args, **kwargs): + self.set_primary_if_first(self) self.keep_is_primary_unique(self) super().save(*args, **kwargs) diff --git a/src/core/tests/test_models.py b/src/core/tests/test_models.py index ffbadc320..5b0e94e3f 100644 --- a/src/core/tests/test_models.py +++ b/src/core/tests/test_models.py @@ -787,3 +787,21 @@ def test_organization_location(self): self.organization_bbk.location, self.location_london, ) + + def test_set_primary_if_first_true(self): + first_affiliation, _created = models.Affiliation.objects.get_or_create( + account=self.t_s_eliot, + organization=self.organization_bbk, + ) + self.assertTrue(first_affiliation.is_primary) + + def test_set_primary_if_first_false(self): + _first_affiliation, _created = models.Affiliation.objects.get_or_create( + account=self.t_s_eliot, + organization=self.organization_bbk, + ) + second_affiliation, _created = models.Affiliation.objects.get_or_create( + account=self.t_s_eliot, + organization=self.organization_rae, + ) + self.assertFalse(second_affiliation.is_primary) diff --git a/src/templates/admin/core/affiliation_display.html b/src/templates/admin/core/affiliation_display.html index fd1e17918..db16059bc 100644 --- a/src/templates/admin/core/affiliation_display.html +++ b/src/templates/admin/core/affiliation_display.html @@ -1,6 +1,6 @@ {% load static %} -
+
{% if affiliation.title_department %} {{ affiliation.title_department }}, {% endif %} @@ -17,4 +17,9 @@ {% else %} {{ affiliation.organization }} {% endif %} + {% if affiliation.is_primary %} + + Primary + + {% endif %}