summaryrefslogtreecommitdiff
path: root/ishtar_common/models_common.py
diff options
context:
space:
mode:
authorÉtienne Loks <etienne.loks@iggdrasil.net>2020-11-17 15:37:22 +0100
committerÉtienne Loks <etienne.loks@iggdrasil.net>2021-02-28 12:15:21 +0100
commit53f899c9ded29921c982e67f220716b2f86823f3 (patch)
treee983fd246f6fd2ce0e9521ea23c1f93c73cc8bc9 /ishtar_common/models_common.py
parent9667957457eaf024e1b4a40f5d04ae001c4eeaca (diff)
downloadIshtar-53f899c9ded29921c982e67f220716b2f86823f3.tar.bz2
Ishtar-53f899c9ded29921c982e67f220716b2f86823f3.zip
Manage a "custom_index" for base types
Diffstat (limited to 'ishtar_common/models_common.py')
-rw-r--r--ishtar_common/models_common.py84
1 files changed, 73 insertions, 11 deletions
diff --git a/ishtar_common/models_common.py b/ishtar_common/models_common.py
index d2e118c7a..4abc81a76 100644
--- a/ishtar_common/models_common.py
+++ b/ishtar_common/models_common.py
@@ -42,7 +42,7 @@ from django.core.serializers import serialize
from django.core.urlresolvers import reverse, NoReverseMatch
from django.core.validators import validate_slug
from django.db import connection
-from django.db.models import Q, Count
+from django.db.models import Q, Count, Max
from django.db.models.signals import post_save, post_delete, m2m_changed
from django.template.defaultfilters import slugify
from django.utils.safestring import SafeText, mark_safe
@@ -62,15 +62,6 @@ from ishtar_common.utils import get_cache, disable_for_loaddata, \
get_all_field_names, merge_tsvectors, cached_label_changed, post_save_geo, \
task, duplicate_item, get_generated_id, get_current_profile
-"""
-from ishtar_common.models import get_external_id, \
- LightHistorizedItem, OwnPerms, Address, post_save_cache, \
- DashboardFormItem, document_attached_changed, SearchAltName, \
- DynamicRequest, GeoItem, QRCodeItem, SearchVectorConfig, DocumentItem, \
- QuickAction, MainItem, Merge
-
-
-"""
logger = logging.getLogger(__name__)
@@ -637,6 +628,18 @@ class HierarchicalType(GeneralType):
lbls.append(item.label)
return " > ".join(reversed(lbls))
+ @property
+ def first_parent(self):
+ parent = self.parent
+ parents = []
+ while parent:
+ if parent in parents: # prevent circular
+ return parent
+ parents.append(parent)
+ if not parent.parent:
+ return parent
+ parent = parent.parent
+
class StatisticItem:
STATISTIC_MODALITIES = [] # example: "year", "operation_type__label"
@@ -2645,6 +2648,7 @@ class CompleteIdentifierItem(models.Model, ImageContainerModel):
HAS_QR_CODE = True
complete_identifier = models.TextField(_("Complete identifier"),
blank=True, null=True)
+ custom_index = models.IntegerField("Custom index", blank=True, null=True)
qrcode = models.ImageField(upload_to=get_image_path, blank=True, null=True,
max_length=255)
@@ -2707,9 +2711,67 @@ class CompleteIdentifierItem(models.Model, ImageContainerModel):
complete_identifier = getattr(self, cached_label_key)
return complete_identifier
+ def generate_custom_index(self, force=False):
+ if not self.pk:
+ return
+ if self.custom_index and not force:
+ return self.custom_index
+ SLUG = getattr(self, "SLUG", None)
+ if not SLUG:
+ return
+ k = SLUG + "_custom_index"
+ profile = get_current_profile()
+ if not hasattr(profile, k):
+ return
+ key = getattr(profile, k)
+ if not key or not key.strip():
+ return
+ keys = key.strip().split(";")
+ if len(key) == 1 and hasattr(self, "get_index_" + key): # custom index
+ # generation
+ return getattr(self, "get_index_" + key)()
+ model = self.__class__
+ try:
+ self_keys = set(
+ list(model.objects.filter(pk=self.pk).values_list(*keys)))
+ except Exception: # bad settings - not managed here
+ return
+ if len(self_keys) != 1: # key is not distinct
+ return
+ self_key = self_keys.pop()
+ return self._get_index(keys, self_key)
+
+ def _get_index(self, keys: list, self_keys: list):
+ model = self.__class__
+ q = model.objects
+ if self.pk:
+ q = model.objects.exclude(pk=self.pk)
+ for idx, key in enumerate(keys):
+ q = q.filter(**{key: self_keys[idx]})
+ try:
+ r = q.aggregate(max_index=Max('custom_index'))
+ except Exception: # bad settings
+ return
+ if not r['max_index']:
+ return 1
+ return r['max_index'] + 1
+
def save(self, *args, **kwargs):
- self.complete_identifier = self.generate_complete_identifier()
super(CompleteIdentifierItem, self).save(*args, **kwargs)
+ if getattr(self, "_prevent_loop", False):
+ return
+ modified = False
+ custom_index = self.generate_custom_index()
+ if custom_index != self.custom_index:
+ modified = True
+ self.custom_index = custom_index
+ complete_id = self.generate_complete_identifier()
+ if complete_id:
+ modified = True
+ self.complete_identifier = complete_id
+ if modified:
+ self._prevent_loop = True
+ self.save()
class SearchVectorConfig: