From 673ce754f6e9e3bd32def6ee8c58dd1d30e3b3a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9ophile=20Bastian?= Date: Sun, 24 Sep 2017 18:41:31 +0200 Subject: [PATCH] Create PublicationYear on API request Closes #3 --- api/views.py | 2 ++ mainsite/models.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/api/views.py b/api/views.py index c2446dd..200ff06 100644 --- a/api/views.py +++ b/api/views.py @@ -78,4 +78,6 @@ def publishApiView(request, data): "Invalid data: {}".format(e)) pub.save() + pub.createPubYear() + return response.HttpResponse("OK") diff --git a/mainsite/models.py b/mainsite/models.py index fd9fb05..a2cbf7a 100644 --- a/mainsite/models.py +++ b/mainsite/models.py @@ -47,6 +47,36 @@ class Publication(models.Model): max_length=128, blank=True) + class NoPublicationYear(Exception): + def __str__(self): + return "No matching publication year." + + @property + def numericPublicationYear(self): + startYear = self.date.year + if self.date.month < 8: + return startYear - 1 + return startYear + + def publicationYear(self): + ''' Fetch corresponding publication year + Raise `NoPublicationYear` if there is no such entry ''' + startYear = self.numericPublicationYear + try: + return PublicationYear.objects.get(startYear=startYear) + except PublicationYear.DoesNotExist: + raise self.NoPublicationYear + + def createPubYear(self): + ''' Creates the corresponding publication year if needed. ''' + if (PublicationYear.objects + .filter(startYear=self.numericPublicationYear).count()) == 0: + pubYear = PublicationYear(startYear=self.numericPublicationYear, + descr='') + pubYear.save() + return True + return False + def __str__(self): if self.custom_name: return self.custom_name