passing variables between methods in class based view

Hello,

Hopefully a simple answer for something which I haven’t been able to find in the documentation.

I have class based view using both get_queryset and get_context_data methods. I’m wanting to check the existence of a dict which may or not be defined in get_queryset to determine whether get_context_data needs to provide some extra content.

class FilterHeadlines(ArchiveIndexView):
    model = Headline
def get_queryset(self, *args, **kwargs):
        queryset = super(FilterHeadlines, self).get_queryset()

        filters = {}

        saved = self.request.GET.get("saved", None)
        if saved is not None:
            filters['marks'] = self.request.user.id

        queryset = Headline.objects.filter(**filters).order_by('-published_date')
        return queryset

def get_context_data(self,*args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
        if filters is not None:
         <<do stuff here>>
        return super().get_context_data(**kwargs)

How do I check whether filters has been defined in get_queryset ? I’ve tried self.filters, but this doesn’t seem to work.

Cheers

The way your code is written, there will always be a dict named filters. But you’re currently defining filters as a local variable, not as a member variable of the class.

If you want to specifically track filters in the class, define (and use) it as self.filters.

Or, you could set saved as a member variable and test it where needed.

Or, you could check self.request.GET in multiple places.

1 Like

Thanks, as per usual @KenWhitesell :slight_smile:

I was able to define self.saved and then could use this in the other method.

Works a treat, thanks again!