Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass extra arguments to nested Serializer in Django Rest Framework

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?

like image 352
vZ10 Avatar asked Aug 12 '16 18:08

vZ10


People also ask

How do you pass extra context data to Serializers in Django REST Framework?

In function-based views, we can pass extra context to serializer with “context” parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with “self. context”. From example, to get “exclude_email_list” we just used code 'exclude_email_list = self.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is nested serializer in Django REST Framework?

DRF provides a Serializer class that gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class that provides a useful shortcut for creating serializers that deal with model instances and querysets.

What is serializing and Deserializing in Django?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


1 Answers

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.

like image 195
vZ10 Avatar answered Nov 14 '22 23:11

vZ10