Django多对多through中间模型反向关联序列化字段缺失问题
问题解决方案
核心错误原因
你混淆了多对多字段related_name和中间表外键反向管理器的作用:
你在Recipe的ingredients多对多字段上定义的related_name='recipe_input',返回的是Product关联的Recipe对象集合,而非中间表RecipeInput的对象集合。而你的ProductInputSerializer是基于RecipeInput模型定义的,传入不匹配的Recipe实例自然无法正确读取字段。
修复步骤
- 调整
ProductSerializer中products_in字段的数据源,改为Django自动为RecipeInput的product外键生成的反向管理器recipeinput_set,它返回的是当前Product关联的所有RecipeInput中间表实例 - 移除
ProductSerializer中冗余的depth=1配置,显式定义的嵌套序列化器不需要自动深度序列化,避免冲突 - (可选)如果不需要超链接字段,可以把
ProductInputSerializer的父类改为serializers.ModelSerializer,避免需要传入request上下文的问题
修改后的核心代码
# 可选修改:如果不需要超链接相关字段,更换父类即可 class ProductInputSerializer(serializers.ModelSerializer): recipe_id = serializers.ReadOnlyField(source='recipe.id') recipe_name = serializers.ReadOnlyField(source='recipe.displayname') class Meta: model = RecipeInput fields = ('recipe_id','recipe_name', 'amount_min', 'amount', ) class ProductSerializer(serializers.ModelSerializer): # 替换source为中间表的反向管理器 products_in = ProductInputSerializer(source='recipeinput_set', many=True, read_only=True) # 如果需要查询该产品作为产出的配方,可新增以下字段 # products_out = ProductOutputSerializer(source='recipeoutput_set', many=True, read_only=True) class Meta: model = Product fields = "__all__" # 移除冗余的depth配置 # depth = 1
修复后即可正常返回products_in中的recipe_id、recipe_name、amount等所有定义的字段。
内容的提问来源于stack exchange,提问作者Eric Jansen
相关产品推荐
相关产品推荐

