43 lines
1.6 KiB
Python
43 lines
1.6 KiB
Python
from rest_framework import serializers
|
|
from .models import CustomObjectDefinition, CustomFieldDefinition, CustomRecord
|
|
from .schema_engine import validate_record_data
|
|
|
|
|
|
class CustomFieldDefinitionSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = CustomFieldDefinition
|
|
fields = '__all__'
|
|
read_only_fields = ['id', 'created_at', 'updated_at']
|
|
|
|
|
|
class CustomObjectDefinitionSerializer(serializers.ModelSerializer):
|
|
fields = CustomFieldDefinitionSerializer(many=True, read_only=True)
|
|
|
|
class Meta:
|
|
model = CustomObjectDefinition
|
|
fields = '__all__'
|
|
read_only_fields = ['id', 'created_at', 'updated_at']
|
|
|
|
|
|
class CustomRecordSerializer(serializers.ModelSerializer):
|
|
class Meta:
|
|
model = CustomRecord
|
|
fields = '__all__'
|
|
read_only_fields = ['id', 'custom_object', 'created_at', 'updated_at']
|
|
|
|
def validate(self, attrs):
|
|
view = self.context.get('view')
|
|
custom_object = attrs.get('custom_object') or getattr(self.instance, 'custom_object', None)
|
|
if not custom_object and view and hasattr(view, 'get_custom_object'):
|
|
custom_object = view.get_custom_object()
|
|
data = attrs.get('data') or getattr(self.instance, 'data', {})
|
|
if custom_object:
|
|
validate_record_data(custom_object, data, partial=self.partial)
|
|
return attrs
|
|
|
|
def update(self, instance, validated_data):
|
|
if self.partial and 'data' in validated_data:
|
|
merged_data = dict(instance.data)
|
|
merged_data.update(validated_data['data'])
|
|
validated_data['data'] = merged_data
|
|
return super().update(instance, validated_data)
|