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

Corrected CustomFieldModelSerializer behavior when serializing lists of objects

This commit is contained in:
Jeremy Stretch
2017-04-04 14:09:14 -04:00
parent d2bd4a213b
commit 99a3e0c399

View File

@ -23,20 +23,27 @@ class CustomFieldModelSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(CustomFieldModelSerializer, self).__init__(*args, **kwargs) def _populate_custom_fields(instance, fields):
custom_fields = {f.name: None for f in fields}
# Retrieve the set of CustomFields which apply to this type of object for cfv in instance.custom_field_values.all():
content_type = ContentType.objects.get_for_model(self.Meta.model)
custom_fields = {f.name: None for f in CustomField.objects.filter(obj_type=content_type)}
# Assign CustomFieldValues from database
for cfv in self.instance.custom_field_values.all():
if cfv.field.type == CF_TYPE_SELECT: if cfv.field.type == CF_TYPE_SELECT:
custom_fields[cfv.field.name] = CustomFieldChoiceSerializer(cfv.value).data custom_fields[cfv.field.name] = CustomFieldChoiceSerializer(cfv.value).data
else: else:
custom_fields[cfv.field.name] = cfv.value custom_fields[cfv.field.name] = cfv.value
instance.custom_fields = custom_fields
self.instance.custom_fields = custom_fields super(CustomFieldModelSerializer, self).__init__(*args, **kwargs)
# Retrieve the set of CustomFields which apply to this type of object
content_type = ContentType.objects.get_for_model(self.Meta.model)
fields = CustomField.objects.filter(obj_type=content_type)
# Populate CustomFieldValues for each instance from database
try:
for obj in self.instance:
_populate_custom_fields(obj, fields)
except TypeError:
_populate_custom_fields(self.instance, fields)
class CustomFieldChoiceSerializer(serializers.ModelSerializer): class CustomFieldChoiceSerializer(serializers.ModelSerializer):