Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def _serialize_instance(self, val_, as_minimal=False):
- """
- Given a model instance, returns its corresponding serialization as
- a Python object.
- Serialization definitions are described at the very beginning of
- this module, under `BASE_SERIALIZERS`.
- Special field names are "*" (a wildcard for "include all fields"),
- "unicode()" (the unicode representation of the current object,
- which then goes mapped into a key named "__unicode__") and
- "unicode(path)" (the unicode representation of an object under
- the given path). If both "path" and "unicode(path)" are defined,
- value for "path" (its ID) will be mapped under "path_id", and the
- stringified version under "path" instead.
- :param val_: The model instance to serialize.
- :type val_: object
- :param as_minimal: Whether to run it in minimal serialization mode (only a subset
- of fields) or not. Default False.
- :type as_minimal: bool
- :returns: A Python-serialized representation of the given object.
- :rtype: dict
- """
- serializer = self._get_scheme(val_)
- fields, exclude = serializer.get_fields(as_minimal), serializer.exclude
- fields = set(fields or ['*'])
- exclude = set(exclude or [])
- base_fields = None if '*' in fields else fields.difference(exclude)
- serialized = serializers.serialize(
- 'python', [val_], fields=base_fields)[0]
- response = Munch(serialized['fields'])
- keys = set(response.keys())
- if '*' in fields:
- # all fields selected
- fields.remove('*')
- fields = fields.union(keys)
- fields = fields.difference(exclude)
- for key in keys:
- if key not in fields:
- del response[key]
- else:
- fields.remove(key)
- for field in fields:
- # unicode(field) -> translates as 'field' in the response,
- # with the field's own ID translated as 'field_id' instead.
- if field.startswith('unicode('):
- field = field[8:-1]
- if not field:
- response['__unicode__'] = str(val_ or '')
- else:
- if field in response:
- id_field = '%s_id' % field
- response[id_field] = response[field]
- response[field] = str(self._run_path(val_, field) or '')
- elif field.startswith('len('):
- # len(field) -> translates as 'field.length' in the response
- field = field[4:-1]
- entry = self._run_path(val_, field)
- if entry is None:
- entry = []
- if isinstance(entry, QuerySet):
- response['%s.length' % field] = entry.count()
- else:
- response['%s.length' % field] = len(entry)
- else:
- if serializer.has_custom(field):
- response[field] = serializer.get_custom(field, val_)
- else:
- response[field] = self._run_path(val_, field)
- if isinstance(response[field], (set, frozenset, tuple)):
- # normalizing types (using lists always)
- # due to JSON serialization issues
- response[field] = list(response[field])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement