diff options
Diffstat (limited to 'ishtar_common')
| -rw-r--r-- | ishtar_common/models.py | 1 | ||||
| -rw-r--r-- | ishtar_common/models_common.py | 98 | ||||
| -rw-r--r-- | ishtar_common/rest.py | 5 | 
3 files changed, 74 insertions, 30 deletions
| diff --git a/ishtar_common/models.py b/ishtar_common/models.py index 442e67429..e72fd2a22 100644 --- a/ishtar_common/models.py +++ b/ishtar_common/models.py @@ -3923,6 +3923,7 @@ class Document(          ),      ]      SERIALIZATION_FILES = ["image", "thumbnail", "associated_file"] +    SERIALIZE_PROPERTIES = ["external_id"]      title = models.TextField(_("Title"), blank=True, default="")      associated_file = models.FileField( diff --git a/ishtar_common/models_common.py b/ishtar_common/models_common.py index 3138cecc6..bf1d10b5a 100644 --- a/ishtar_common/models_common.py +++ b/ishtar_common/models_common.py @@ -40,8 +40,12 @@ 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  from django.utils.translation import activate, deactivate -from ishtar_common.utils import ugettext_lazy as _, pgettext_lazy, get_image_path, \ -    human_date +from ishtar_common.utils import ( +    ugettext_lazy as _, +    pgettext_lazy, +    get_image_path, +    human_date, +)  from simple_history.models import HistoricalRecords as BaseHistoricalRecords  from simple_history.signals import (      post_create_historical_record, @@ -1209,7 +1213,7 @@ class HistoricalRecords(BaseHistoricalRecords):              history_type=history_type,              history_user=history_user,              history_change_reason=history_change_reason, -            **attrs +            **attrs,          )          pre_create_historical_record.send( @@ -3245,19 +3249,15 @@ class ShortMenuItem:          return "" -class MainItem(ShortMenuItem): -    """ -    Item with quick actions available from tables -    Extra actions are available from sheets -    """ - -    QUICK_ACTIONS = [] +class SerializeItem:      SERIALIZE_EXCLUDE = ["search_vector"]      SERIALIZE_PROPERTIES = ["external_id", "multi_polygon_geojson", "point_2d_geojson"]      SERIALIZE_CALL = {}      SERIALIZE_DATES = [] +    SERIALIZATION_FILES = [] +    SERIALIZE_STRING = [] -    def full_serialize(self) -> dict: +    def full_serialize(self, recursion=False) -> dict:          """          API serialization          :return: data dict @@ -3265,36 +3265,75 @@ class MainItem(ShortMenuItem):          full_result = {}          serialize_fields = []          for field in self._meta.get_fields(): -            if field.name in self.SERIALIZE_EXCLUDE: +            field_name = field.name +            if field_name in self.SERIALIZE_EXCLUDE:                  continue              if field.many_to_one or field.one_to_one:                  try: -                    value = getattr(self, field.name) +                    value = getattr(self, field_name)                  except (MultipleObjectsReturned, ObjectDoesNotExist):                      value = None                  if value: -                    value = str(value) +                    if ( +                        field_name not in self.SERIALIZE_STRING +                        and hasattr(value, "full_serialize") +                        and not recursion +                    ): +                        # print(field.name) +                        value = value.full_serialize(recursion=True) +                    elif field_name in self.SERIALIZATION_FILES: +                        try: +                            value = {"url": value.url} +                        except ValueError: +                            value = None +                    else: +                        value = str(value)                  else:                      value = None -                full_result[field.name] = value +                full_result[field_name] = value              elif field.many_to_many: -                values = getattr(self, field.name) +                values = getattr(self, field_name)                  if values.count(): -                    values = [str(v) for v in values.all()] +                    first_value = values.all()[0] +                    if ( +                        field_name not in self.SERIALIZE_STRING +                        and hasattr(first_value, "full_serialize") +                        and not recursion +                    ): +                        # print(field.name) +                        values = [ +                            v.full_serialize(recursion=True) for v in values.all() +                        ] +                    else: +                        if first_value in self.SERIALIZATION_FILES: +                            values = [] +                            for v in values: +                                try: +                                    values.append({"url": value.url}) +                                except ValueError: +                                    pass +                        else: +                            values = [str(v) for v in values.all()]                  else:                      values = [] -                full_result[field.name] = values +                full_result[field_name] = values              else: -                serialize_fields.append(field.name) +                if field_name in self.SERIALIZATION_FILES: +                    value = getattr(self, field_name) +                    try: +                        value = {"url": value.url} +                    except ValueError: +                        value = None +                    full_result[field.name] = value +                else: +                    serialize_fields.append(field_name) -        result = json.loads(serialize( -            "json", -            [self], -            fields=serialize_fields -        )) +        result = json.loads(serialize("json", [self], fields=serialize_fields))          full_result.update(result[0]["fields"]) +        if "main_image" in full_result: +            print(full_result["main_image"])          for prop in self.SERIALIZE_PROPERTIES: -            if prop not in full_result: +            if hasattr(self, prop) and prop not in full_result:                  full_result[prop] = getattr(self, prop)          if "point_2d_geojson" in full_result:              full_result["point_2d"] = True @@ -3330,6 +3369,15 @@ class MainItem(ShortMenuItem):              lst.append(["-" if v is None else v for v in values])          return lst + +class MainItem(ShortMenuItem, SerializeItem): +    """ +    Item with quick actions available from tables +    Extra actions are available from sheets +    """ + +    QUICK_ACTIONS = [] +      @classmethod      def class_verbose_name(cls):          return cls._meta.verbose_name diff --git a/ishtar_common/rest.py b/ishtar_common/rest.py index b0498cea6..90f61f2aa 100644 --- a/ishtar_common/rest.py +++ b/ishtar_common/rest.py @@ -172,9 +172,4 @@ class GetAPIView(generics.RetrieveAPIView):              return Response({}, content_type="json")          obj = q.all()[0]          result = obj.full_serialize() -        """ -        result = generic_get_results( -            [self.model], "", no_geo=False, result_queryset={self.model.__name__: q} -        ) -        """          return Response(result, content_type="json") | 
