Skip to content

Provide an override-able get_queryset in JWTAuthentication #903

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

Open
SafaAlfulaij opened this issue Apr 5, 2025 · 2 comments
Open

Provide an override-able get_queryset in JWTAuthentication #903

SafaAlfulaij opened this issue Apr 5, 2025 · 2 comments

Comments

@SafaAlfulaij
Copy link

SafaAlfulaij commented Apr 5, 2025

In JWTAuthentication.get_user, the user is retrieved using the objects manager directly, without providing an easy way to customize the queryset:

try:
user = self.user_model.objects.get(**{api_settings.USER_ID_FIELD: user_id})
except self.user_model.DoesNotExist as e:
raise AuthenticationFailed(
_("User not found"), code="user_not_found"
) from e

Currently, the only way for users to modify the queryset is by overriding the entire method—something that's discouraged due to maintainability and future compatibility concerns.

Introducing a get_queryset method would allow developers to tailor the queryset for different scenarios (e.g. annotating users who hold a valid license) for further checks and validations, without performing extra database queries.

This pattern aligns with how Django REST Framework typically works—it relies on get_ methods (like get_queryset) that return default values unless explicitly overridden:
https://github.com/encode/django-rest-framework/blob/c41314f1fc898490f27e1015cc859e28afe6f7b9/rest_framework/generics.py#L52-L92

@vgrozdanic
Copy link
Contributor

What is the use case where you would want to use get_queryset and not just fetch the user by id_field (which is customizable)?

@rohitrhmn1
Copy link

Suppose you have a custom User value which you want to annotate. Example:

User.objects.annotate(has_wallet_value=Q(wallet__value__gte=50)).order_by()

Now in this case, whenever we would like to use these in views, for example,

if self.request.user.has_wallet_value: 
#... do something

If the get_queryset method is provided inside the authentication class, then we could easily subclass it and override it with custom method.

Hope this helps!!

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

3 participants