[Fixed]-AttributeError when serializing relationship with 'through' table

1👍

the simplest way to change that is change the source of your steps in RecipeSerializer

class RecipeSerializer(serializers.HyperlinkedModelSerializer):

    steps = StepInfoSerializer(many=True, read_only=True, source='stepinfo_set')

now I will make an explanation about that.

first, only in the Django world.

for example, rec is an instance object of Recipe Model.

Get the difference of the two statement.

rec.steps.all()
rec.stepinfo_set.all()

rec.steps.all() will returns an array of Step object instance, make sure it’s the target model of ManyToManyField, not the through model.

if you want to access through model, you need to visit from the related_name of the ForeignKey refer to current model in the Through Model (StepInfo Model).

later, I will add an example with related_name.

since in your StepInfo does not specify the related_name, so django will automatically give you a default related_name stepinfo_set. (this name is that one in the first snippet).

so will return back to how to get through instances. just rec.setpinfo_set.all().

All right, in the end, I suggest you add the related_name to your ForeignKey in your Through Models.

class StepInfo(BaseModel):

    recipe = models.ForeignKey('Recipe', related_name='stepinfos')
    step = models.ForeignKey(Step, related_name='stepinfos')
    step_number = models.IntegerField()

class RecipeSerializer(serializers.HyperlinkedModelSerializer):

    steps = StepInfoSerializer(many=True, read_only=True, source='stepinfos')

Leave a comment