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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With