Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serializer missing context if nested in another Serializer #2471

Closed
brianmay opened this issue Jan 27, 2015 · 1 comment
Closed

Serializer missing context if nested in another Serializer #2471

brianmay opened this issue Jan 27, 2015 · 1 comment

Comments

@brianmay
Copy link

Hello,

Am trying to hide fields on a serializer if the user does not have permission to access them. I think I saw somewhere that recommended doing this within the serializer's init function, so I wrote the following:

class AlbumSerializer(serializers.ModelSerializer):                             

    def __init__(self, *args, **kwargs):
        super(AlbumSerializer, self).__init__(*args, **kwargs)
        request = self.context['request']
        if not request.user.is_staff:
            del self.fields['revised']
            del self.fields['revised_utc_offset']

      class Meta:
        model = models.album                             

This is nested in another serializer like as such:

class PhotoSerializer(serializers.ModelSerializer):
    albums = AlbumSerializer(many=True, read_only=True)

The problem being this doesn't pass the required context parameter. In fact the object gets constructed in the global scope before request is made available.

At one point I got confused with #2355, however I think this is unrelated.

Trouble is I can't actually think of a good solution to this :-(

Thanks

@tomchristie
Copy link
Member

.context is available during serialization and deserialization - you're correct that it won't be available during init for a nested serializer.

For this sort of use case I'd suggest either:

  • Customize get_serializer_class, return a different serializer depending on request.user.is_staff`.

  • Customize get_serializer and use that to dynamically alter the fields. eg...

    serializer = super(ExampleView, self).get_serializer(_args, *_kwargs)
    if ...:
    del serializer.fields['albums']['revised']
    del serializer.fields['albums']['revised_utc_offset']
    return serializer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants