resfframework中修改序列化類的返回值

在序列化類中重寫to_representation(self,instance)方法,這個是返回json對象的方法,返回的是一個待序列化的對象,能夠直接對這個類進行定製,有關關聯查詢也能夠在這裏進行定製,例如git

    def to_representation(self, instance):
        res = super().to_representation(instance=instance)
        res["gitGroup"] = {"name": instance.gitGroup.name}
        res["project"] = {"name": instance.project.name}
        res["project2"] = instance.project.name
        return res
相關文章
相關標籤/搜索