[Answered ]-Using the results from a query in BOTH the templates and the view

1πŸ‘

βœ…

Is there a way to somehow β€˜centralize’ the query and have it run only once, and still inserting it into the template file AND having it available within the function of the view?

QuerySets are lazy constructing a queryset will not make a database request, you make a query to the database if you consume the queryset, for example by enumerating over it, calling str(…), repr(…) and len(…) on it, check its truthiness with bool(…) or in an if/elif clause.

If you thus use a context processor that passes the filtered queryset to the template, and you do not use the queryset in a way described above, that will not make a query. Furthermore if the data is passed to the context, it will override the data in the context processor. So you can add it to the context in case you already evaluated it in the view, to prevent making a second database query you thus override this in the context, such that there is no reference to the "other" queryset, and the result is reused.

You need to be careful not to construct a new query if the one is evaluated. For example if qs is an evaluated queryset, you should work with qs again, if you work with qs.all() this will make a new QuerySet that will then make a query to the database.

Leave a comment