I need to pass a Tag object to the template, but without an additional query to the database in get_context_data method.
Can you please tell me if there is a more elegant way to get the value from the get_queryset method in the get_context_data.
And if there is a more elegant way, is it correct to declare your own fields in Django views
class PostListView(ListView):
model = Post
paginate_by = 3
context_object_name = 'posts'
template_name = 'blog/post/list.html'
tag = None
def get_queryset(self):
data = super().get_queryset()
if tag_slug := self.kwargs.get('tag_slug'):
self.tag = get_object_or_404(Tag, slug=tag_slug)
data = data.filter(tags__in=[self.tag])
return data
def get_context_data(self, *, object_list=None, **kwargs):
data = super().get_context_data(**kwargs)
data['tag'] = self.tag
return data
Based on reply I edit my code for the following:
because I need tag name and it can be different from tug slug I override get method to get tag object and not execute uselees code later
removed query from get_queryset
replaced "object_list" with "posts" due to iterating through posts in my template