1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00
Files
netbox-community-netbox/netbox/extras/api/serializers.py

57 lines
2.1 KiB
Python
Raw Normal View History

2016-03-01 11:23:03 -05:00
from rest_framework import serializers
2016-08-22 17:15:20 -04:00
from extras.models import CF_TYPE_SELECT, CustomFieldChoice, Graph
2016-08-22 13:20:30 -04:00
2016-08-22 15:16:49 -04:00
class CustomFieldSerializer(serializers.Serializer):
2016-08-22 13:20:30 -04:00
"""
Extends a ModelSerializer to render any CustomFields and their values associated with an object.
"""
custom_fields = serializers.SerializerMethodField()
def get_custom_fields(self, obj):
2016-08-22 15:16:49 -04:00
# Gather all CustomFields applicable to this object
2016-08-22 13:20:30 -04:00
fields = {cf.name: None for cf in self.context['view'].custom_fields}
2016-08-22 15:16:49 -04:00
# Attach any defined CustomFieldValues to their respective CustomFields
2016-08-22 13:20:30 -04:00
for cfv in obj.custom_field_values.all():
2016-08-22 15:16:49 -04:00
2016-08-22 17:15:20 -04:00
# Attempt to suppress database lookups for CustomFieldChoices by using the cached choice set from the view
2016-08-22 15:16:49 -04:00
# context.
2016-08-22 17:15:20 -04:00
if cfv.field.type == CF_TYPE_SELECT and hasattr(self, 'custom_field_choices'):
2016-08-22 15:16:49 -04:00
cfc = {
'id': int(cfv.serialized_value),
'value': self.context['view'].custom_field_choices[int(cfv.serialized_value)]
}
fields[cfv.field.name] = CustomFieldChoiceSerializer(instance=cfc).data
2016-08-22 17:15:20 -04:00
# Fall back to hitting the database in case we're in a view that doesn't inherit CustomFieldModelAPIView.
elif cfv.field.type == CF_TYPE_SELECT:
fields[cfv.field.name] = CustomFieldChoiceSerializer(instance=cfv.value).data
2016-08-22 13:20:30 -04:00
else:
fields[cfv.field.name] = cfv.value
2016-08-22 15:16:49 -04:00
2016-08-22 13:20:30 -04:00
return fields
class CustomFieldChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = CustomFieldChoice
fields = ['id', 'value']
2016-03-01 11:23:03 -05:00
class GraphSerializer(serializers.ModelSerializer):
embed_url = serializers.SerializerMethodField()
embed_link = serializers.SerializerMethodField()
2016-03-01 11:23:03 -05:00
class Meta:
model = Graph
fields = ['name', 'embed_url', 'embed_link']
2016-03-01 11:23:03 -05:00
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'])