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

Django序列化嵌套外键对象为JSON仅返回主键问题求解

问题原因

你当前代码的错误来自三个核心问题:

  1. DRF序列化器的调用方式完全错误:serialize()是Django原生序列化模块的方法,不是DRF ModelSerializer 类的内置方法
  2. 冗余配置:你已经显式声明了section字段关联ForumSectionSerializer,不需要额外加depth = 1配置
  3. 序列化器create方法参数缺失DRF要求的self参数(仅读取场景下不影响运行,但写入场景会报错)

修正方案

第一步:修正serializers.py代码

from rest_framework import serializers
from .models import *

class ForumSectionSerializer(serializers.ModelSerializer):
    class Meta:
        model = ForumSection
        fields = '__all__'

    # 补全self参数
    def create(self, validated_data):
        return ForumSection.objects.create(**validated_data)
      
class ForumSubSectionSerializer(serializers.ModelSerializer):
    section = ForumSectionSerializer(read_only=True)
    # 可选配置:如果需要提交数据时传入section的ID创建记录,可以加下面这行
    # section_id = serializers.PrimaryKeyRelatedField(queryset=ForumSection.objects.all(), write_only=True, source='section')
   
    class Meta:
        model = ForumSubSection
        fields = ['pk', 'title', 'description', 'order', 'section']
        # 删掉冗余的depth=1

    # 补全self参数
    def create(self, validated_data):
        return ForumSubSection.objects.create(**validated_data)

第二步:修正视图调用代码

def ajax_edit_forum_subsection(request):
    # 建议加select_related预查询关联表,避免N+1查询问题
    qs = ForumSubSection.objects.select_related('section').order_by('pk')
    # 序列化查询集(多个对象)必须加many=True参数
    ser = ForumSubSectionSerializer(qs, many=True)
    # 直接取序列化器的data属性即可得到序列化后的Python原生数据结构
    return JsonResponse(ser.data, safe=False)

输出示例

修正后返回的JSON格式会符合你的要求,关联的版块信息会完整输出:

[
  {
    "pk": 1,
    "title": "新手提问区",
    "description": "新人疑问请发到这里",
    "order": 1,
    "section": {
      "id": 2,
      "title": "社区交流",
      "description": "用户交流讨论版块",
      "order": 1
    }
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 23:54:00