2017-03-08 16:18:41 -05:00
|
|
|
from django.contrib.contenttypes.models import ContentType
|
|
|
|
|
|
|
|
from rest_framework import serializers
|
|
|
|
|
2017-04-04 11:25:23 -04:00
|
|
|
from extras.models import CF_TYPE_SELECT, CustomField, CustomFieldChoice, CustomFieldValue
|
2017-03-08 16:18:41 -05:00
|
|
|
|
|
|
|
|
|
|
|
#
|
|
|
|
# Custom fields
|
|
|
|
#
|
|
|
|
|
2017-04-04 11:25:23 -04:00
|
|
|
class CustomFieldsSerializer(serializers.BaseSerializer):
|
2017-03-08 16:18:41 -05:00
|
|
|
|
2017-04-04 11:25:23 -04:00
|
|
|
def to_representation(self, obj):
|
|
|
|
return obj
|
2017-03-08 16:18:41 -05:00
|
|
|
|
|
|
|
|
|
|
|
class CustomFieldModelSerializer(serializers.ModelSerializer):
|
2017-04-04 11:25:23 -04:00
|
|
|
"""
|
|
|
|
Extends ModelSerializer to render any CustomFields and their values associated with an object.
|
|
|
|
"""
|
|
|
|
custom_fields = CustomFieldsSerializer()
|
2017-03-08 16:18:41 -05:00
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
|
|
|
|
super(CustomFieldModelSerializer, self).__init__(*args, **kwargs)
|
|
|
|
|
2017-04-04 11:25:23 -04:00
|
|
|
# Retrieve the set of CustomFields which apply to this type of object
|
2017-03-08 16:18:41 -05:00
|
|
|
content_type = ContentType.objects.get_for_model(self.Meta.model)
|
2017-04-04 11:25:23 -04:00
|
|
|
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:
|
|
|
|
custom_fields[cfv.field.name] = CustomFieldChoiceSerializer(cfv.value).data
|
|
|
|
else:
|
|
|
|
custom_fields[cfv.field.name] = cfv.value
|
|
|
|
|
|
|
|
self.instance.custom_fields = custom_fields
|
2017-03-08 16:18:41 -05:00
|
|
|
|
|
|
|
|
|
|
|
class CustomFieldChoiceSerializer(serializers.ModelSerializer):
|
2017-04-04 11:25:23 -04:00
|
|
|
"""
|
|
|
|
Imitate utilities.api.ChoiceFieldSerializer
|
|
|
|
"""
|
|
|
|
value = serializers.IntegerField(source='pk')
|
|
|
|
label = serializers.CharField(source='value')
|
2017-03-08 16:18:41 -05:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = CustomFieldChoice
|
2017-04-04 11:25:23 -04:00
|
|
|
fields = ['value', 'label']
|