React/Django应用程序:需要在后端中使用自定义功能在POT路线中更新一个字段,然后再用serialializer保存
我正在尝试使用自己的功能更改字段的内容。我正在使用一个简化的函数,该功能在每个单词之间添加逗号。我希望能够将我的逗号句子发送到前端,但我不知道如何使用Django文档中给出的序列化器来做到这一点。我在网上找不到任何试图在线执行此操作的示例。我还需要在后端执行此操作,因为我的其他一些自定义功能需要访问特定的Python库。
这是我的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)
这是我的api> 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)
这是我的api> Serializers.py
from rest_framework.serializers import ModelSerializer
from .models import Lines
class LineSerializer(ModelSerializer):
class Meta:
model = Lines
fields = '__all__'
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__'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您是通过直接在实例上调用模型实例,然后在序列化器上再次调用它。序列化保存方法将执行保存模型实例本身。关于使用串行序列保存实例的文档: https:https:https:// wwwww。 django-rest-framework.org/api-guide/serializers/#saving-instances
要实现您要做的事情,您应该创建一个自定义的序列化器字段,可能称为
translation flastion field
,然后覆盖to_internal_value
方法在将数据持续到数据库之前执行字符串突变,或覆盖to_representation
,该将在从串行器返回数据之前执行字符串突变。这取决于您是否希望在通过序列化器获取数据时使用逗号或添加逗号。自定义字段上的文档此处: https> https:///www.django -rest-framework.org/api-guide/fields/#custom-fields一旦设置自定义字段,您就不会在
accentline
视图中执行任何突变,而只需通过像这样向序列化要求数据First and foremost, you are calling save on the model instance twice by calling it directly on the instance, and then again on the serializer. The serializer save method will perform save on the model instance itself. Docs on saving instances with serializers: https://www.django-rest-framework.org/api-guide/serializers/#saving-instances
To achieve what you want to do you should create a custom serializer field probably called
TranslationField
and either override theto_internal_value
method to perform your string mutations before the data is persisted to the database, or overrideto_representation
which will perform the string mutations before the data is returned from the serializer. It depends on if you wish to persist the field... with commas or add the commas when getting the data via serializer. Docs on custom fields here: https://www.django-rest-framework.org/api-guide/fields/#custom-fieldsOnce you set up your custom field you will not perform any mutations in your
accentLine
view and instead simply pass the request data to the serializer like so