I'm trying to change the content of a field with my own function. I'm using a simplified function that adds commas between each word. I want to be able to send my comma-fied sentence to the frontend but I don't know how to do that with the serializer that was given in Django documentation. I can't find any examples online of someone trying to do this online. I also need to do this in the backend because some of my other custom functions need access to a specific python library.
Here is my api > views.py
@api_view(['PUT'])
def accentLine(request, pk):
data = request.data
line = Lines.objects.get(id=pk)
if data['accent'] == 'shatner':
shatnerLine = line.content.replace(' ', ', ')
line.translation = shatnerLine
line.save()
serializer = LineSerializer(instance=line, data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
Here is my api > models.py
class Lines(models.Model):
# userId = models.ForeignKey(Users, on_delete=models.CASCADE)
script = models.ForeignKey(Scripts, null=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=50, null=True)
content = models.TextField(max_length=5000, null=True)
accent = models.CharField(max_length=50, default='english')
translation = models.TextField(max_length=5000, null=True)
updatedAt = models.DateField(auto_now=True)
Here is my api > serializers.py
from rest_framework.serializers import ModelSerializer
from .models import Lines
class LineSerializer(ModelSerializer):
class Meta:
model = Lines
fields = '__all__'