demluckycharms
demluckycharms

Reputation: 421

Django - return multiple querysets in view

Django 1.10

In my view, I have a function get_queryset() that, currently, returns one queryset. This function is called from another function, get_context(), which takes that data, uses it to get some values, and returns everything to the front end.

However, I now want to return 2 querysets from get_queryset(), one that is the full queryset and one that has a filter applied to it.

I assumed I could simply do something like:

full_results = query.all()
# do some filtering
filter_results = full_results.someFilter()

return full_results, filter_results

However, I have another function where these results get sent to FIRST before being sent to the front end. I figured I would be able to access these querysets easily with bracket notation, like this -

faceted = self.get_queryset()[0].facet('thing')

However! Turns out that I am unable to do so. I am trying to access a property on each item in the queryset in this second django function but am getting an error -

AttributeError: 'SearchQuerySet' object has no attribute 'feature'

So clearly I am doing something wrong. Is it possible to do what I am trying to do? Or would it be better to just make another function to return this data?

Upvotes: 2

Views: 3159

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600041

You can only return a single queryset from get_queryset. But get_context_data itself can be extended to add whatever you like.

def get_context_data(self, *args, **kwargs):
    context = super().get_context_data(*args, **kwargs)
    context['filter_results'] = context['full_results'].someFilter()
    return context

Upvotes: 4

Related Questions