简体   繁体   English

React / Django App:需要在使用序列化程序保存之前更新放置路由中的字段,在后端使用自定义函数

[英]React/Django App: Need to update a field in a put route, with a custom function in the backend, before saving with a serializer

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.我希望能够将我的逗号语句发送到前端,但我不知道如何使用 Django 文档中给出的序列化程序来做到这一点。 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.我还需要在后端执行此操作,因为我的其他一些自定义函数需要访问特定的 python 库。

Here is my api > views.py这是我的 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这是我的 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这是我的 api > serializers.py

from rest_framework.serializers import ModelSerializer
from .models import Lines

class LineSerializer(ModelSerializer):
    class Meta:
        model = Lines
        fields = '__all__'

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.首先,您在模型实例上调用 save 两次,方法是直接在实例上调用它,然后在序列化程序上再次调用它。 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关于使用序列化程序保存实例的文档: 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 the to_internal_value method to perform your string mutations before the data is persisted to the database, or override to_representation which will perform the string mutations before the data is returned from the serializer.要实现您想要做的事情,您应该创建一个可能称为TranslationField的自定义序列化程序字段,并覆盖to_internal_value方法以在数据持久化到数据库之前执行字符串突变,或者覆盖to_representation它将在数据之前执行字符串突变从序列化程序返回。 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-fields此处有关自定义字段的文档: https ://www.django-rest-framework.org/api-guide/fields/#custom-fields

Once 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设置自定义字段后,您将不会在您的accentLine视图中执行任何更改,而是只需将请求数据传递给序列化程序,如下所示

@api_view(['PUT'])
def accentLine(request, pk):
    data = request.data
    line = Lines.objects.get(id=pk)

    serializer = LineSerializer(instance=line, data=data)

    if serializer.is_valid():
        serializer.save()

    return Response(serializer.data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 django 自定义序列化程序字段不起作用 - django custom serializer field not working Django Rest Framework v3.0:如何在保存对象时将自定义序列化程序字段映射到模型字段? - Django Rest Framework v3.0 : How to map custom serializer fields to model field while saving an object? Django Rest Framework –序列化程序中的“自定义超链接”字段 - Django Rest Framework – Custom Hyperlink field in serializer Django Rest Framework模型序列化程序自定义字段 - Django Rest Framework Model Serializer Custom Field Django Rest序列化器的自定义字段顺序? - Django Rest Order on custom field from serializer? django-rest-auth:自定义注册序列化程序不保存自定义字段 - django-rest-auth: Custom Register Serializer not saving custom fields 在Django中保存序列化器 - Saving a Serializer in Django django rest 框架序列化程序将字段值保存为空字符串,但没有错误 - django rest framework serializer saving field value as empty strings, but no errors 如何在django rest框架中将绝对url字段放在序列化器模型中? - how to put absolute url field in serializer model in django rest framework? Django Rest PUT请求序列化程序无法使用外键更新模型 - Django rest PUT request serializer fails to update model with foreign key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM