get context data in get_queryset?

I have BaseContex and Listview which is for Searching in multiple models, Search Class inherits from BaseContext. I set the current user to context and want to use it in my def get_queryset method, But it doesn’t work. Search CBV get_context_data execute after get_queryset that’s why, self.user is None. Please note that the USERS model is a custom model and it is not related to the Django user model.

class BaseContext(ContextMixin):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        request = self.request
        if request.COOKIES.get('token') is not None:
            ...
            user = Users.objects.filter(user_id=user_id).first()
            context.update({'current_user': user})
            context.update({'is_logged_in ': True})
        else:
            context.update({'is_logged_in ': False})
        return context

class Search(BaseContext, ListView):
    template_name = 'search.html'
    context_object_name = "results"
    paginate_by = 15
    user = None

    def get_queryset(self):
        query = self.request.GET.get('search', None)
        if query is not None and self.user is not None:
            ...
            return queryset_chain
        return faqModel.objects.none()

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        if 'is_logged_in' in context and context['is_logged_in']:
            self.user = context['current_user']
        else:
            redirect("index")

        return context

My question is how can I get context data in def get_queryset(self) ? or is there alternative solution, for building paginated list like this?
Note: I also asked this question in stackoverflow

You don’t, nor do you need to.

As you point out, get_context_data is called after get_queryset.

The method, get_context_data is not for “you” to get any context data. It’s for you to create context data to be passed to the template.

The setup method of a ListView sets three attributes on self, request, args, and kwargs. You have that information available to you in the get_queryset method.

Therefore, as an example, if you have user_id as a keyword arg in your url, you cacn do the following in get_queryset:

user = Users.objects.get(user_id=self.kwargs['user_id'])
1 Like

Thanks, I understand.

Nope, user_id is not in the URL. But it is an option, I can use this solution.
But I wonder, is there any option to get user_id in my Search view, which user_id set from BaseContext?

The BaseContext code you’ve provided here doesn’t show where/how you’re getting a value for user_id. But the short answer is you can get the value for user in get_queryset in the same way you’re getting it in BaseContext.