If i have a nested serializer:
class ChildSerializer(ModelSerializer):
class Meta:
fields = ('c_name', )
model = Child
class ParentSerializer(ModelSerializer):
child = ChildSerializer(many=True, read_only=True)
class Meta:
model = Parent
fields = ('p_name', 'child')
And i want to access the context in the nested serializer, how can i do that? As far as i can tell, context isn't passed to the Child.
I want to be able to implement a permission model per user on fields, for that i overridden the get_fields() method of the ModelSerializer:
def get_fields(self):
fields = super().get_fields()
....
for f in fields:
if has_rights(self.context['request'].user, f, "read"):
ret_val[f] = fields[f]
....
return ret_val
Which works for regular serializers, but the context, and thus the request and user are not available when the nested child is passed to get_fields(). How do i access the context when the serializer is nested?
I know this is an old question, but I had the same question in 2019. Here is my solution:
In the above, I create a serializer base class that overrides
get_fields()
and passesself._context
to any child serializer that has the same base class. For ListSerializers, I attach the context to the child of it.Then, I check for a query param "omit_data" and remove the "data" field if it's requested.
I hope this is helpful for anybody still looking for answers for this.
You can use
serialziers.ListField
instead.ListField
automatically passes context to it's child. So, here's your codeIf 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 :Ok i found a working solution. I replaced the ChildSerializer assignment in the Parent class with a SerializerMethodField which adds the context. This is then passed to the get_fields method in my CustomModelSerializer:
and in my CustomModelSerializer:
This seems to work fine, and fields of the child are discarded in the serializer when i either revoke read-rights on Child.c_name or on Parent.child