Calculating serializers read only fields

Here is an example:

class MyModel(models.Model):
    metadata = models.JSONField()

class MetadataSerializer(serializers.Serializer):
    x = serializers.IntegerField()
    y = serializers.IntegerField(read_only=True)

class MyAPIView(APIView):
    def post(self, request):
        serializer = MetadataSerializer(
        return Response(status=201)

I would like to calculate y based on x using "complex" business logic y = const * x and save result to json field.

Q: Where should i place this business logic?

  • before serializer init, intercepting immutable
  • inside serializer validate() or validate_y() method.
  • using get_y() of SerializerMethodField.
  • inside create_mymodel() service.
Back to Top