class CableSerializer(ValidatedModelSerializer): termination_a_type = ContentTypeField() termination_b_type = ContentTypeField() termination_a = serializers.SerializerMethodField(read_only=True) termination_b = serializers.SerializerMethodField(read_only=True) status = ChoiceField(choices=CONNECTION_STATUS_CHOICES, required=False) length_unit = ChoiceField(choices=CABLE_LENGTH_UNIT_CHOICES, required=False) class Meta: model = Cable fields = [ 'id', 'termination_a_type', 'termination_a_id', 'termination_a', 'termination_b_type', 'termination_b_id', 'termination_b', 'type', 'status', 'label', 'color', 'length', 'length_unit', ] def _get_termination(self, obj, side): """ Serialize a nested representation of a termination. """ if side.lower() not in ['a', 'b']: raise ValueError("Termination side must be either A or B.") termination = getattr(obj, 'termination_{}'.format(side.lower())) if termination is None: return None serializer = get_serializer_for_model(termination, prefix='Nested') context = {'request': self.context['request']} data = serializer(termination, context=context).data return data def get_termination_a(self, obj): return self._get_termination(obj, 'a') def get_termination_b(self, obj): return self._get_termination(obj, 'b')
class CableSerializer(TaggedObjectSerializer, ValidatedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='dcim-api:cable-detail') termination_a_type = ContentTypeField( queryset=ContentType.objects.filter(CABLE_TERMINATION_MODELS)) termination_b_type = ContentTypeField( queryset=ContentType.objects.filter(CABLE_TERMINATION_MODELS)) termination_a = serializers.SerializerMethodField(read_only=True) termination_b = serializers.SerializerMethodField(read_only=True) status = ChoiceField(choices=CableStatusChoices, required=False) length_unit = ChoiceField(choices=CableLengthUnitChoices, allow_blank=True, required=False) class Meta: model = Cable fields = [ 'id', 'url', 'termination_a_type', 'termination_a_id', 'termination_a', 'termination_b_type', 'termination_b_id', 'termination_b', 'type', 'status', 'label', 'color', 'length', 'length_unit', 'tags', ] def _get_termination(self, obj, side): """ Serialize a nested representation of a termination. """ if side.lower() not in ['a', 'b']: raise ValueError("Termination side must be either A or B.") termination = getattr(obj, 'termination_{}'.format(side.lower())) if termination is None: return None serializer = get_serializer_for_model(termination, prefix='Nested') context = {'request': self.context['request']} data = serializer(termination, context=context).data return data @swagger_serializer_method(serializer_or_field=serializers.DictField) def get_termination_a(self, obj): return self._get_termination(obj, 'a') @swagger_serializer_method(serializer_or_field=serializers.DictField) def get_termination_b(self, obj): return self._get_termination(obj, 'b')
class ObjectChangeSerializer(serializers.ModelSerializer): user = NestedUserSerializer(read_only=True) content_type = ContentTypeField(read_only=True) changed_object = serializers.SerializerMethodField(read_only=True) class Meta: model = ObjectChange fields = [ 'id', 'time', 'user', 'user_name', 'request_id', 'action', 'content_type', 'changed_object', 'object_data', ] def get_changed_object(self, obj): """ Serialize a nested representation of the changed object. """ if obj.changed_object is None: return None serializer = get_serializer_for_model(obj.changed_object, prefix='Nested') if serializer is None: return obj.object_repr context = {'request': self.context['request']} data = serializer(obj.changed_object, context=context).data return data
class GraphSerializer(ValidatedModelSerializer): type = ContentTypeField( queryset=ContentType.objects.filter(GRAPH_MODELS), ) class Meta: model = Graph fields = ['id', 'type', 'weight', 'name', 'template_language', 'source', 'link']
class GraphSerializer(ValidatedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='extras-api:graph-detail') type = ContentTypeField( queryset=ContentType.objects.filter(FeatureQuery('graphs').get_query()), ) class Meta: model = Graph fields = ['id', 'url', 'type', 'weight', 'name', 'template_language', 'source', 'link']
class GraphSerializer(ValidatedModelSerializer): type = ContentTypeField(queryset=ContentType.objects.filter( FeatureQuery('graphs').get_query()), ) class Meta: model = Graph fields = [ 'id', 'type', 'weight', 'name', 'template_language', 'source', 'link' ]
class ImageAttachmentSerializer(ValidatedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='extras-api:imageattachment-detail') content_type = ContentTypeField(queryset=ContentType.objects.all()) parent = serializers.SerializerMethodField(read_only=True) class Meta: model = ImageAttachment fields = [ 'id', 'url', 'content_type', 'object_id', 'parent', 'name', 'image', 'image_height', 'image_width', 'created', ] def validate(self, data): # Validate that the parent object exists try: data['content_type'].get_object_for_this_type(id=data['object_id']) except ObjectDoesNotExist: raise serializers.ValidationError( "Invalid parent object: {} ID {}".format( data['content_type'], data['object_id'])) # Enforce model validation super().validate(data) return data @swagger_serializer_method(serializer_or_field=serializers.DictField) def get_parent(self, obj): # Static mapping of models to their nested serializers if isinstance(obj.parent, Device): serializer = NestedDeviceSerializer elif isinstance(obj.parent, Rack): serializer = NestedRackSerializer elif isinstance(obj.parent, Site): serializer = NestedSiteSerializer else: raise Exception( "Unexpected type of parent object for ImageAttachment") return serializer(obj.parent, context={ 'request': self.context['request'] }).data
class IPAddressSerializer(TaggedObjectSerializer, CustomFieldModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='ipam-api:ipaddress-detail') family = ChoiceField(choices=IPAddressFamilyChoices, read_only=True) vrf = NestedVRFSerializer(required=False, allow_null=True) tenant = NestedTenantSerializer(required=False, allow_null=True) status = ChoiceField(choices=IPAddressStatusChoices, required=False) role = ChoiceField(choices=IPAddressRoleChoices, allow_blank=True, required=False) assigned_object_type = ContentTypeField( queryset=ContentType.objects.filter(IPADDRESS_ASSIGNMENT_MODELS), required=False, allow_null=True) assigned_object = serializers.SerializerMethodField(read_only=True) nat_inside = NestedIPAddressSerializer(required=False, allow_null=True) nat_outside = NestedIPAddressSerializer(read_only=True) class Meta: model = IPAddress fields = [ 'id', 'url', 'family', 'address', 'vrf', 'tenant', 'status', 'role', 'assigned_object_type', 'assigned_object_id', 'assigned_object', 'nat_inside', 'nat_outside', 'dns_name', 'description', 'tags', 'custom_fields', 'created', 'last_updated', ] read_only_fields = ['family'] @swagger_serializer_method(serializer_or_field=serializers.DictField) def get_assigned_object(self, obj): if obj.assigned_object is None: return None serializer = get_serializer_for_model(obj.assigned_object, prefix='Nested') context = {'request': self.context['request']} return serializer(obj.assigned_object, context=context).data
class RenderedGraphSerializer(serializers.ModelSerializer): embed_url = serializers.SerializerMethodField(read_only=True) embed_link = serializers.SerializerMethodField(read_only=True) type = ContentTypeField(read_only=True) class Meta: model = Graph fields = ['id', 'type', 'weight', 'name', 'embed_url', 'embed_link'] def get_embed_url(self, obj): return obj.embed_url(self.context['graphed_object']) def get_embed_link(self, obj): return obj.embed_link(self.context['graphed_object'])
class ImageAttachmentSerializer(ValidatedModelSerializer): content_type = ContentTypeField() parent = serializers.SerializerMethodField(read_only=True) class Meta: model = ImageAttachment fields = [ 'id', 'content_type', 'object_id', 'parent', 'name', 'image', 'image_height', 'image_width', 'created', ] def validate(self, data): # Validate that the parent object exists try: data['content_type'].get_object_for_this_type(id=data['object_id']) except ObjectDoesNotExist: raise serializers.ValidationError( "Invalid parent object: {} ID {}".format( data['content_type'], data['object_id'])) # Enforce model validation super(ImageAttachmentSerializer, self).validate(data) return data def get_parent(self, obj): # Static mapping of models to their nested serializers if isinstance(obj.parent, Device): serializer = NestedDeviceSerializer elif isinstance(obj.parent, Rack): serializer = NestedRackSerializer elif isinstance(obj.parent, Site): serializer = NestedSiteSerializer else: raise Exception( "Unexpected type of parent object for ImageAttachment") return serializer(obj.parent, context={ 'request': self.context['request'] }).data
class ExportTemplateSerializer(ValidatedModelSerializer): content_type = ContentTypeField( queryset=ContentType.objects.filter(EXPORTTEMPLATE_MODELS), ) template_language = ChoiceField( choices=TemplateLanguageChoices, default=TemplateLanguageChoices.LANGUAGE_JINJA2 ) class Meta: model = ExportTemplate fields = [ 'id', 'content_type', 'name', 'description', 'template_language', 'template_code', 'mime_type', 'file_extension', ]
class JobResultSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='extras-api:jobresult-detail') user = NestedUserSerializer( read_only=True ) status = ChoiceField(choices=JobResultStatusChoices, read_only=True) obj_type = ContentTypeField( read_only=True ) class Meta: model = JobResult fields = [ 'id', 'url', 'created', 'completed', 'name', 'obj_type', 'status', 'user', 'data', 'job_id', ]
class ExportTemplateSerializer(ValidatedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='extras-api:exporttemplate-detail') content_type = ContentTypeField( queryset=ContentType.objects.filter(FeatureQuery('export_templates').get_query()), ) template_language = ChoiceField( choices=TemplateLanguageChoices, default=TemplateLanguageChoices.LANGUAGE_JINJA2 ) class Meta: model = ExportTemplate fields = [ 'id', 'url', 'content_type', 'name', 'description', 'template_language', 'template_code', 'mime_type', 'file_extension', ]
class NestedObjectPermissionSerializer(WritableNestedSerializer): url = serializers.HyperlinkedIdentityField( view_name='users-api:objectpermission-detail') object_types = ContentTypeField(queryset=ContentType.objects.all(), many=True) groups = serializers.SerializerMethodField(read_only=True) users = serializers.SerializerMethodField(read_only=True) class Meta: model = ObjectPermission fields = [ 'id', 'url', 'name', 'enabled', 'object_types', 'groups', 'users', 'actions' ] def get_groups(self, obj): return [g.name for g in obj.groups.all()] def get_users(self, obj): return [u.username for u in obj.users.all()]
class ObjectChangeSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='extras-api:objectchange-detail') user = NestedUserSerializer(read_only=True) action = ChoiceField(choices=ObjectChangeActionChoices, read_only=True) changed_object_type = ContentTypeField(read_only=True) changed_object = serializers.SerializerMethodField(read_only=True) class Meta: model = ObjectChange fields = [ 'id', 'url', 'time', 'user', 'user_name', 'request_id', 'action', 'changed_object_type', 'changed_object_id', 'changed_object', 'object_data', ] @swagger_serializer_method(serializer_or_field=serializers.DictField) def get_changed_object(self, obj): """ Serialize a nested representation of the changed object. """ if obj.changed_object is None: return None try: serializer = get_serializer_for_model(obj.changed_object, prefix='Nested') except SerializerNotFound: return obj.object_repr context = {'request': self.context['request']} data = serializer(obj.changed_object, context=context).data return data
class ObjectPermissionSerializer(ValidatedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='users-api:objectpermission-detail') object_types = ContentTypeField( queryset=ContentType.objects.all(), many=True ) groups = SerializedPKRelatedField( queryset=Group.objects.all(), serializer=NestedGroupSerializer, required=False, many=True ) users = SerializedPKRelatedField( queryset=User.objects.all(), serializer=NestedUserSerializer, required=False, many=True ) class Meta: model = ObjectPermission fields = ( 'id', 'url', 'name', 'description', 'enabled', 'object_types', 'groups', 'users', 'actions', 'constraints', )