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