def to_native(self, value): if not value: return None args = [serializers.get_component(value, arg) for arg in self.args] kwargs = dict((arg, serializers.get_component(value, arg)) for arg in self.kwargs) locale = getattr(value, 'locale', settings.LANGUAGE_CODE) path = reverse(self.url_name, locale=locale, args=args, kwargs=kwargs) return '%s%s' % (settings.SITE_URL, path)
def field_to_native(self, obj, field_name): """ Override default so that the serializer can be used as a nested field across relationships. """ from rest_framework.serializers import ObjectDoesNotExist, get_component, is_simple_callable if self.source == '*': return self.to_native(obj) try: source = self.source or field_name value = obj for component in source.split('.'): value = get_component(value, component) if value is None: break except ObjectDoesNotExist: return None if is_simple_callable(getattr(value, 'all', None)): return self.many_to_native(value.all()) if value is None: return None if self.many is not None: many = self.many else: many = hasattr(value, '__iter__') and not isinstance(value, (Page, dict, six.text_type)) if many: return self.many_to_native(value) return self.to_native(value)
def initialize(self, parent, field_name): """ Called to set up a field prior to field_to_native or field_from_native. parent - The parent serializer. field_name - The name of the field being initialized. Prepares a queryset for the model field by using the default manager. Properly supports dot-separated field names (e.g. 'booking.owner') """ field_name = 'booking.owner' # TODO: the code below should be provided upstream to fix the multi-component field names super(RelatedField, self).initialize(parent, field_name) if self.queryset is None and not self.read_only: model = self.parent.opts.model for component in field_name.split('.'): field = get_component(model, component) if hasattr(field, 'related'): # Forward model = field.related.model else: # Reverse model = field.field.rel.to self.queryset = model._default_manager.all()
def field_to_native(self, obj, field_name): """ Given and object and a field name, returns the value that should be serialized for that field. Display the choice label. """ if obj is None: return self.empty if self.source == '*': return self.to_native(obj) source = self.source or field_name value = obj components = source.split('.') for component in components: if component == components[-1]: # last item, fetch human readable form component = 'get_{0}_display'.format(component) value = get_component(value, component) if value is None: break return self.to_native(value.lower())