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

accessing request object in method field? #12

Closed
philippeluickx opened this issue Jan 9, 2016 · 2 comments
Closed

accessing request object in method field? #12

philippeluickx opened this issue Jan 9, 2016 · 2 comments

Comments

@philippeluickx
Copy link

I provide data based on the user that is currently authenticated.
With DRF I simply access self.context.request. I see the serializer accepts the context object, but leaves it at None. Is this a choice by design or a feature to be implemented?
Dealbreaker for me in any case.

In terms of performance testing, FYI I am getting 50% gains compared to DRF. Which is significant and would be great to have in prod...!

@clarkduvall
Copy link
Owner

The context argument was added to the constructor to be compatible with DRF generic views and is currently not used. You can make a custom base serializer that sets the context, and then you'll be able to access it later:

class BaseSerializer(Serializer):
    def __init__(self, instance=None, many=False, data=None, context=None, **kwargs):
        self.context = context
        super(BaseSerializer, self).__init__(instance, many, data, context, **kwargs)

# Then in your serializer:
class MySerializer(BaseSerializer):
    foo = MethodField()

    def get_foo(self, obj):
        # Access self.context

>>> MySerializer(obj, context=context).data

Glad you're seeing significant performance gains!

@philippeluickx
Copy link
Author

Thanks, will try that!

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