8

I have such serializer:

 class FirstModelSerializer(serializers.ModelSerializer):

       secondModel = SecondModelSerializer()

       class Meta:
            model = FirstModel
            fields = '__all__'

Where secondModel is ManyToMany field of FirstModel.

Is there any way to pass FirstModel object id to SecondModelSerializer?

1 Answer 1

15

It was easier then I thought. I just had to use context like this

class FirstModelSerializer(serializers.ModelSerializer):

      secondModel = SerializerMethodField()

      class Meta:
            model = FirstModel
            fields = '__all__'

      def get_secondModel(self, obj):
          return SecondModelSerializer(obj.secondModel.all(), many=True, context={'first_model_id': obj.id)).data

And use self.context.get('first_model_id') in SecondModelSerializer to get to this id.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.