django rest framework nested modelserializer
Asked Answered
N

2

9

this is realted to my other question
django-rest-framework, multitable model inheritance, ModelSerializers and nested serializers

In django rest framework we can define nested model serializer like so

class OtherModelSerializer(serializer.ModelSerializer):
    mybasemodel_set = MyBaseModelSerializer(many=True)

    class Meta:
        model = OtherModel

when we create an OtherModelSerializer, the MyBaseModelSerializer is instantiated before __init__ is run. I believe this is the case because if I override the __init__() of MyBaseModelSerializer and check "instance", it is None.

My question is when and how does MyBaseModelSerializer get passed the queryset or instance for mybasemodel_set?

My goal here is to override what happens when we do this.

Necrotomy answered 5/6, 2014 at 18:19 Comment(0)
L
0

This line

mybasemodel_set = MyBaseModelSerializer(many=True)

Will initialize an instance of class MyBaseModelSerializer and pass many=True as parameter.


How does MyBaseModelSerializer get passed the queryset or instance?

I am not 100% sure what are you trying to do but most probably

class MyBaseModelSerializer(serializers.ModelSerializer):
     def to_representation(self, instance):
         pass

Is the function you are looking for. You will be given an instance and expected to return serialized data.

http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior

Leverrier answered 28/1, 2016 at 16:26 Comment(0)
A
0

While Instantiating, MyBaseModelSerializer does not have access to the queryset or instance of mybasemodel_set. It is only aware of its parent serializer (OtherModelSerializer).

The queryset or instance for mybasemodel_set is passed when OtherModelSerializer is initialized with data, such as during serialization or deserialization. At this point, OtherModelSerializer retrieves the related objects for mybasemodel_set based on the provided instance or queryset.

If you want to override the behavior of MyBaseModelSerializer when it receives the related objects for mybasemodel_set, you can override methods like to_representation() or to_internal_value() within MyBaseModelSerializer.

Alehouse answered 14/3 at 19:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.