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

Extended API to include custom fields

This commit is contained in:
Jeremy Stretch
2016-08-22 13:20:30 -04:00
parent b14afaa687
commit 76f0463290
14 changed files with 139 additions and 74 deletions

View File

@@ -1,6 +1,29 @@
from rest_framework import serializers
from extras.models import Graph
from extras.models import CF_TYPE_SELECT, CustomFieldChoice, Graph
class CustomFieldsSerializer(serializers.Serializer):
"""
Extends a ModelSerializer to render any CustomFields and their values associated with an object.
"""
custom_fields = serializers.SerializerMethodField()
def get_custom_fields(self, obj):
fields = {cf.name: None for cf in self.context['view'].custom_fields}
for cfv in obj.custom_field_values.all():
if cfv.field.type == CF_TYPE_SELECT:
fields[cfv.field.name] = CustomFieldChoiceSerializer(instance=cfv.value).data
else:
fields[cfv.field.name] = cfv.value
return fields
class CustomFieldChoiceSerializer(serializers.ModelSerializer):
class Meta:
model = CustomFieldChoice
fields = ['id', 'value']
class GraphSerializer(serializers.ModelSerializer):

View File

@@ -1,9 +1,8 @@
import graphviz
from rest_framework import generics
from rest_framework.views import APIView
import tempfile
from wsgiref.util import FileWrapper
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q
from django.http import Http404, HttpResponse
from django.shortcuts import get_object_or_404
@@ -15,6 +14,17 @@ from extras.models import Graph, TopologyMap, GRAPH_TYPE_INTERFACE, GRAPH_TYPE_P
from .serializers import GraphSerializer
class CustomFieldModelAPIView(object):
"""
Include the applicable set of CustomField in the view context.
"""
def __init__(self):
super(CustomFieldModelAPIView, self).__init__()
self.content_type = ContentType.objects.get_for_model(self.queryset.model)
self.custom_fields = self.content_type.custom_fields.all()
class GraphListView(generics.ListAPIView):
"""
Returns a list of relevant graphs