使用Django REST框架获取与基础模型实例相关的所有模型的序列化响应

问题描述

我有3个模型

def blogpost(request,slug):

    variable=Post.objects.filter(slug=slug).first()
    comments=Comments.objects.filter(post=variable,parent=None)
    replys=Comments.objects.filter(post=variable).exclude(parent=None)
    replyDict={}
    for reply in replys:
        if reply.parent.sno not in replyDict.keys():
            replyDict[reply.parent.sno]=[reply]
        else:
            replyDict[reply.parent.sno].append(reply)
    return render(request,"blog/blogpost.html",{'blog':variable,'comments':comments,'user':request.user,"replys":replyDict})

模型 Project 中的每个条目都与 Calculation 模型中的2个条目相连。此外,计算的每个条目都与财务模型

的4个条目相关

有什么方法可以仅通过使用基本 Project 模型的primary_key来获得序列化响应?

解决方法

所需的只是将项目实例传递到项目序列化程序中

project_instance = Project.objects.get(id=project_id)
serializer = ProjectSerializer(instance=project_instance)
return Response(serializer.data,status=status.HTTP_200_OK)