customfields.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from django.contrib.contenttypes.models import ContentType
  2. from rest_framework.fields import Field
  3. from rest_framework.serializers import ValidationError
  4. from extras.choices import CustomFieldTypeChoices
  5. from extras.models import CustomField
  6. from netbox.constants import NESTED_SERIALIZER_PREFIX
  7. #
  8. # Custom fields
  9. #
  10. class CustomFieldDefaultValues:
  11. """
  12. Return a dictionary of all CustomFields assigned to the parent model and their default values.
  13. """
  14. requires_context = True
  15. def __call__(self, serializer_field):
  16. self.model = serializer_field.parent.Meta.model
  17. # Retrieve the CustomFields for the parent model
  18. content_type = ContentType.objects.get_for_model(self.model)
  19. fields = CustomField.objects.filter(content_types=content_type)
  20. # Populate the default value for each CustomField
  21. value = {}
  22. for field in fields:
  23. if field.default is not None:
  24. value[field.name] = field.default
  25. else:
  26. value[field.name] = None
  27. return value
  28. class CustomFieldsDataField(Field):
  29. def _get_custom_fields(self):
  30. """
  31. Cache CustomFields assigned to this model to avoid redundant database queries
  32. """
  33. if not hasattr(self, '_custom_fields'):
  34. content_type = ContentType.objects.get_for_model(self.parent.Meta.model)
  35. self._custom_fields = CustomField.objects.filter(content_types=content_type)
  36. return self._custom_fields
  37. def to_representation(self, obj):
  38. # TODO: Fix circular import
  39. from utilities.api import get_serializer_for_model
  40. data = {}
  41. for cf in self._get_custom_fields():
  42. value = cf.deserialize(obj.get(cf.name))
  43. if value is not None and cf.type == CustomFieldTypeChoices.TYPE_OBJECT:
  44. serializer = get_serializer_for_model(cf.object_type.model_class(), prefix=NESTED_SERIALIZER_PREFIX)
  45. value = serializer(value, context=self.parent.context).data
  46. elif value is not None and cf.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
  47. serializer = get_serializer_for_model(cf.object_type.model_class(), prefix=NESTED_SERIALIZER_PREFIX)
  48. value = serializer(value, many=True, context=self.parent.context).data
  49. data[cf.name] = value
  50. return data
  51. def to_internal_value(self, data):
  52. if type(data) is not dict:
  53. raise ValidationError(
  54. "Invalid data format. Custom field data must be passed as a dictionary mapping field names to their "
  55. "values."
  56. )
  57. # If updating an existing instance, start with existing custom_field_data
  58. if self.parent.instance:
  59. data = {**self.parent.instance.custom_field_data, **data}
  60. return data