I want to display the following two views in a template index.html
.
class IndexView(generic.ListView):
template_name = 'items/index.html'
context_object_name = 'popular_items_list'
def get_queryset(self):
return Item.objects.order_by('-rating')[:5]
class tryView(generic.ListView):
template_name = 'items/index.html'
context_object_name = 'latest_items_list'
def get_queryset(self):
return Item.objects.order_by('pub_date')[:5]
Is there a way to combine these two views into one view?
How should I get both query sets displayed on index.html
?
Is it possible to send all the Item.objects.all()
and filter in the template?
A few questions here, let me answer the first.
You can overwrite get_context_data
and add to the context of the template for more items in one view. For example...
class IndexView(generic.ListView):
template_name = 'items/index.html'
context_object_name = 'popular_items_list'
def get_queryset(self):
return Item.objects.order_by('-rating')[:5]
def get_context_data(self, *args, **kwargs):
context = super(IndexView, self).get_context_data(*args, **kwargs)
context['moreItems'] = Item.objects.order_by('pub_date')[:5]
return context
This way you can include multiple query sets on a page/template as required. In this example moreItems
would be available in your template along with popular_items_list
In regards to the second question, yes you can pass in the URL arguments and use them to filter the queryset. I suggest reading up on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With