context in nested serializers django rest framework

后端 未结 5 2058
有刺的猬
有刺的猬 2021-01-07 16:35

If i have a nested serializer:

class ChildSerializer(ModelSerializer):
    class Meta:
        fields = (\'c_name\', )
        model = Child


class ParentSe         


        
5条回答
  •  春和景丽
    2021-01-07 17:07

    If you can not change the nature of you child serializer, as in @Kirill Cherepanov and @Robin van Leeuwen answers, a light but not full-integrated solution would be to manually pass the context in __init__() function :

    class ChildSerializer(CustomModelSerializer):
        class Meta:
            fields = ('c_name', )
            model = Child
    
    
    class ParentSerializer(CustomModelSerializer):
    
        child = ChildSerializer(many=True, read_only=True)
    
        class Meta:
            model = Parent
            fields = ('p_name', 'child')
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # We pass the "upper serializer" context to the "nested one"
            self.fields['child'].context.update(self.context)
    

提交回复
热议问题