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

Django Serializer多对多字段返回空列表,如何修复?

解决Product序列化器中lessons字段为空的问题

1. 修复视图中的变量名错误

你的LessonListView的get_queryset方法存在变量名拼写错误,products_view未定义,导致查询集无法正常返回。修改后的代码:

class LessonListView(ListAPIView):
    serializer_class = ProductSerializer
    permission_classes = [permissions.IsAuthenticated]
    def get_queryset(self):
        # 直接返回正确的查询集,或纠正变量名
        return Product.objects.all()

2. 预取关联的lessons数据

多对多关联字段默认不会自动预加载,使用prefetch_related可一次性加载关联数据,既避免N+1查询问题,也能确保序列化器正确获取关联的Lesson数据:

class LessonListView(ListAPIView):
    serializer_class = ProductSerializer
    permission_classes = [permissions.IsAuthenticated]
    def get_queryset(self):
        # 预取lessons关联数据
        return Product.objects.prefetch_related('lessons').all()

3. 验证数据库中的关联关系

如果以上修改后字段仍为空,需确认数据库中是否已建立Product和Lesson的关联:

  • 进入Django Shell:python manage.py shell
  • 执行命令检查关联:
# 获取目标Product
product = Product.objects.get(id=1)
# 查看关联的Lesson列表
print(product.lessons.all())

若输出为空,说明未建立关联,需手动添加:

# 获取要关联的Lesson
lesson = Lesson.objects.get(id=1)
# 添加关联
product.lessons.add(lesson)
# 保存修改
product.save()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:57:53