def to_representation(self, instance): result = super(SessionDetailsSerializer, self).to_representation(instance) return serializers.OrderedDict([( key, result[key] if result[key] is not None else serializers.OrderedDict([]), ) for key in result])
def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, dict): message = self.error_messages['invalid'].format( datatype=type(data).__name__) raise serializers.ValidationError( {api_settings.NON_FIELD_ERRORS_KEY: [message]}) ret = serializers.OrderedDict() errors = serializers.OrderedDict() fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) result = copy.copy(data) if hasattr(field, 'key') and field.key is not None: if isinstance(field, BindableListSerializer) or isinstance( field, serializers.Field): for step in field.key.split('.'): result = result.get(step, {}) if not isinstance(result, dict): result = {field.field_name: result} primitive_value = field.get_value(result) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except serializers.ValidationError as exc: errors[field.field_name] = exc.detail except serializers.DjangoValidationError as exc: errors[field.field_name] = list(exc.messages) except serializers.SkipField: pass else: serializers.set_value(ret, field.source_attrs, validated_value) if errors: raise serializers.ValidationError(errors) return ret
def to_representation(self, value): """Serialize translated fields. Simply iterate over available translations and, for each language, delegate serialization logic to the translation model serializer. """ if value is None: return # Only need one serializer to create the native objects serializer = self.serializer_class() # Split into a dictionary per language result = serializers.OrderedDict() for translation in value.all(): # value = translations related manager result[translation.language_code] = serializer.to_representation( translation) if settings.PARLER_REST_SHOW_EXCLUDED_LANGUAGE_TABS: existing_languages = [lg_code for lg_code in result] settings_languages = [ language[0] for language in settings.LANGUAGES ] empty_languages = [ lg_code for lg_code in settings_languages if lg_code not in existing_languages ] for lg_code in empty_languages: result[lg_code] = dict() for field in serializer.fields: result[lg_code][field] = '' return result
def to_representation(self, value): """Serialize translated fields. Simply iterate over available translations and, for each language, delegate serialization logic to the translation model serializer. """ if value is None: return # Only need one serializer to create the native objects serializer = self.serializer_class() # Split into a dictionary per language result = serializers.OrderedDict() for translation in value.all(): # value = translations related manager result[translation.language_code] = serializer.to_representation( translation) return result
def to_representation(self, instance): ret = super(DisplayNameModelSerializer, self).to_representation(instance) return serializers.OrderedDict(filter(lambda x: not x[1] is None, ret.items()))
class AlertAPISerializer(serializers.ModelSerializer): class Meta: model = Alert fields = ('contract', 'abi') contract = serializers.CharField() abi = serializers.ListField() events = serializers.OrderedDict() def to_internal_value(self, data): filtered_data = {} # ABI if data.get('abi'): abi = None try: if not isinstance(json.loads(data.get('abi')), list): raise serializers.ValidationError( {'abi': 'This field is required.'}) except Exception as e: raise serializers.ValidationError( {'abi': 'This field is required.'}) filtered_data['abi'] = data.get('abi') else: raise serializers.ValidationError( {'abi': 'This field is required.'}) # Contract if data.get('contract'): filtered_data['contract'] = data.get('contract') else: raise serializers.ValidationError( {'contract': 'This field is required.'}) # Events if data.get('events'): filtered_data['events'] = [] events = data.get('events') filtered_events = dict() for key, values in events.iteritems(): # Event Name event_name = key filtered_events[event_name] = {} if values: for innerkey, innervalues in values.iteritems(): filtered_events[event_name][innerkey] = innervalues filtered_data['events'] = filtered_events return filtered_data def create(self, validated_data): # Create the objects eventvalue_obj = None event_obj = None alert_obj = None try: alert_obj = Alert.objects.get( dapp__authentication_code=self.context['request'].auth. authentication_code, contract=validated_data.get('contract')) except Alert.DoesNotExist: alert_obj = Alert() alert_obj.abi = validated_data.get('abi') alert_obj.dapp = self.context['request'].auth alert_obj.contract = validated_data.get('contract') alert_obj.save() if validated_data.get('events'): events_obj = Event.objects.filter(alert=alert_obj.id) events_obj.delete() for key in validated_data.get('events'): properties_dict = validated_data.get('events').get(key) event_obj = Event() event_obj.name = key event_obj.alert = alert_obj event_obj.save() for propertykey, propertyvalue in properties_dict.iteritems(): # Event Value object eventvalue_obj = EventValue() eventvalue_obj.property = propertykey eventvalue_obj.value = propertyvalue eventvalue_obj.event = event_obj eventvalue_obj.save() else: # Delete Alert when no Events in request body alert_obj.delete() return alert_obj def to_representation(self, instance): return {}
class BaseActivityListSerializer(ModelSerializer): title = serializers.CharField(allow_blank=True, required=False) status = FSMField(read_only=True) permissions = ResourcePermissionField('activity-detail', view_args=('pk', )) owner = ResourceRelatedField(read_only=True) is_follower = serializers.SerializerMethodField() type = serializers.CharField(read_only=True, source='JSONAPIMeta.resource_name') stats = serializers.OrderedDict(read_only=True) goals = ResourceRelatedField(required=False, many=True, queryset=ImpactGoal.objects.all()) slug = serializers.CharField(read_only=True) included_serializers = { 'initiative': 'bluebottle.initiatives.serializers.InitiativeListSerializer', 'image': 'bluebottle.activities.serializers.ActivityImageSerializer', 'owner': 'bluebottle.initiatives.serializers.MemberSerializer', 'goals': 'bluebottle.impact.serializers.ImpactGoalSerializer', 'goals.type': 'bluebottle.impact.serializers.ImpactTypeSerializer', } def get_is_follower(self, instance): user = self.context['request'].user return bool(user.is_authenticated) and instance.followers.filter( user=user).exists() class Meta(object): model = Activity fields = ( 'type', # Needed for old style API endpoints like pages / page blocks 'slug', 'id', 'image', 'initiative', 'owner', 'title', 'description', 'is_follower', 'status', 'stats', 'goals', ) meta_fields = ( 'permissions', 'created', 'updated', ) class JSONAPIMeta(object): included_resources = [ 'owner', 'initiative', 'image', 'initiative.image', 'initiative.location', 'initiative.place', 'goals', 'goals.type', ] resource_name = 'activities'