我有一台Student型的.我想要更新一些特定的字段.但是,当我要更新一个或两个字段,但另一个字段的值不变时,哪些字段没有更改,这些字段会显示这个错误**"此字段是必需的."**

Here is my model.

class Student(models.Model):
    teacher=models.ForeignKey(Teacher, on_delete=models.CASCADE)
    name=models.CharField(max_length=20)
    level=models.CharField(max_length=20)

And here are my views

class StudentUpdateDelete(APIView): 
    def patch(self, request, id):
        student=Student.objects.filter(pk=id).first()
        serializer=StudentSerializer(student, data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Avobe模型有3个字段,但我只想使用补丁方法更改name个字段.

here is postman request image

推荐答案

如果要使用PATCH方法更新特定字段,请在初始化serializer时设置partial=True.

因此,对于您的观点来说,它将是:

class StudentUpdateDelete(APIView): 
    def patch(self, request, id):
        student=Student.objects.filter(pk=id).first()
        serializer=StudentSerializer(student, data=request.data, partial=True)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Python相关问答推荐

为什么判断pd.DataFrame的值与判断pd.Series的值存在差异(如果索引中有值)?

只需使用Python在图像中保留 colored颜色 范围区域

调试回归无法解决我的问题

如何在Power Query中按名称和时间总和进行分组

从单个列创建多个列并按pandas分组

Polars:使用列值引用when / then表达中的其他列

根据网格和相机参数渲染深度

使用FASTCGI在IIS上运行Django频道

使可滚动框架在tkinter环境中看起来自然

发生异常:TclMessage命令名称无效.!listbox"

Python库:可选地支持numpy类型,而不依赖于numpy

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

try 将一行连接到Tensorflow中的矩阵

我想一列Panadas的Rashrame,这是一个URL,我保存为CSV,可以直接点击

使用Python更新字典中的值

如何在图中标记平均点?

Python逻辑操作作为Pandas中的条件

Pandas Data Wrangling/Dataframe Assignment

使用Python查找、替换和调整PDF中的图像'

人口全部乱序 - Python—Matplotlib—映射