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

Queryset based on request #2292

Closed
stevelacey opened this issue Dec 17, 2014 · 4 comments
Closed

Queryset based on request #2292

stevelacey opened this issue Dec 17, 2014 · 4 comments

Comments

@stevelacey
Copy link

I am just upgrading to DRF 3.0, and I am pretty much there.

One thing for the upgrade docs / helping me... how do I contextualise the queryset now required for related fields to the request?

At ViewSet level, for the results, remains easy:

    def get_queryset(self):
        if self.request.user.is_staff:
            queryset = Book.objects.all()
        else:
            queryset = self.request.user.library.books.all()

        return queryset

But when customising the choices for a relation in a serializer:

    book = SlugRelatedField(queryset=Book.objects.all(), slug_field='isbn')
    #                                    ^ how request here? lambda... magic?
@tomchristie
Copy link
Member

Conversation on this here: #1985.
You can dynamically alter the .fields attribute on a serializer instance, so you could modify your serializer .__init__ in order to do this, but we do need a better answer to this, which will probably be a part of dealing with #1811.
Closing this issue off in preference of those existing ones.

@stevelacey
Copy link
Author

Overriding __init__ in my serializer worked a treat, thanks:

    def __init__(self, *args, **kwargs):
        user = kwargs['context']['request'].user

        if not user.is_staff:
            book_f = self.fields['book']

            book_f.queryset = book_f.queryset.filter(organisation=user.organisation)

        super(ExampleSerializer, self).__init__(*args, **kwargs)

@stevelacey
Copy link
Author

@tomchristie is there any better approach for this yet? I am running into a bunch of issues caused largely by requiring the request in serializers – e.g. django-rest-swagger wants to access the fields for introspection and doesn't pass a context along

@tomchristie
Copy link
Member

e.g. django-rest-swagger wants to access the fields for introspection and doesn't pass a context along

In which case I'd suggest overriding get_serializer instead, and modifying the field at that point.
That way it's happening in the context of a view, rather than implicitly requiring request in the context.

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