You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django REST Framework的ModelViewSet中重写update返回关联Author?

问题描述

以下是示例模型:

class Author(models.Model):
    name = models.CharField(max_length=5)  # 注:原代码中`max_lenght`为拼写错误,正确应为`max_length`

class Post(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)  # 注:原代码中`max_lenght`为拼写错误,正确应为`max_length`
    body = models.TextField()

对应的视图如下:

class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostStatSerializer

当前对PostViewSet执行update/put操作可成功完成,但期望更新Post记录后,用AuthorSerializer返回其关联的Author记录,请问如何重写update动作实现该功能?

解决方案

直接重写PostViewSet中的update方法,完成Post更新后,获取关联的Author实例并序列化返回即可,代码实现如下:

from rest_framework.response import Response

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostStatSerializer

    def update(self, request, *args, **kwargs):
        # 执行父类update逻辑,完成Post记录更新
        super().update(request, *args, **kwargs)
        # 获取更新后的Post实例
        post = self.get_object()
        # 用AuthorSerializer序列化关联的Author
        author_serializer = AuthorSerializer(post.author)
        # 返回序列化后的Author数据
        return Response(author_serializer.data)

补充说明

  • 上述代码继承了父类的错误处理逻辑,只有Post更新成功时才会返回Author数据,更新失败时会保持原有错误返回机制。
  • 建议修正模型代码中max_lenght的拼写错误,避免后续出现字段验证或存储问题。

内容的提问来源于stack exchange,提问作者Jitendra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:30:57