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

Django API查询Product时included_lessons仅返回ID,如何获取完整对象?

解决Django REST Framework中ManyToMany字段返回完整对象列表的问题

核心原因

默认情况下,DRF的ModelSerializer对多对多字段会使用PrimaryKeyRelatedField,仅返回关联对象的ID列表。要返回完整对象,需要显式指定关联字段的序列化方式。

具体解决步骤

  1. 创建Lesson模型的序列化器
    先定义LessonSerializer,明确要返回的Lesson字段:

    from rest_framework import serializers
    from .models import Lesson
    
    class LessonSerializer(serializers.ModelSerializer):
        class Meta:
            model = Lesson
            fields = ['id', 'name', 'something else']  # 替换为你实际需要的Lesson字段
    
  2. 修改ProductSerializer
    在ProductSerializer中,将included_lessons字段指定为LessonSerializer,并设置many=True适配多对多关系:

    class ProductSerializer(serializers.ModelSerializer):
        included_lessons = LessonSerializer(many=True)
        
        class Meta:
            model = Product
            fields = '__all__'
    
  3. 优化查询性能(可选但推荐)
    在视图中使用prefetch_related预加载关联的Lesson数据,避免N+1数据库查询问题:

    class ProductApiView(viewsets.ReadOnlyModelViewSet):
        queryset = Product.objects.all().prefetch_related('included_lessons')
        serializer_class = ProductSerializer
    

效果验证

修改完成后,included_lessons字段会返回包含指定字段的完整Lesson对象列表,与你期望的返回格式一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:13:34