Difference between get_context_data and get_queryset and code improvement (Django)

1

I wanted to know the difference between get_context_data and get_queryset.

And I'd like to hear from you about my codes.

What is right and what is wrong with them?

link

class SaleDetailView(DetailView):
    template_name = 'vendas/sale/sale_detail.html'
    model = Sale

    def get_context_data(self, **kwargs):
        s = Sale.objects.get(pk=self.kwargs['pk'])
        sd = SaleDetail.objects.all().filter(sale=s)
        context = super(SaleDetailView, self).get_context_data(**kwargs)
        context['count'] = sd.count()
        context['Sale'] = s
        context['Itens'] = sd
        return context

link

def get_queryset(self):
    p = Product.objects.all()
    q = self.request.GET.get('search_box')
    # buscar por produto
    if q is not None:
        p = p.filter(product__icontains=q)
    # filtra produtos em baixo estoque
    if self.request.GET.get('filter_link', False):
        p = p.filter(stock__lt=F('stock_min'))
    return p

What can be improved on these codes?

    
asked by anonymous 18.06.2015 / 04:20

1 answer

1

These methods have totally different purposes:

  • get_context_data provides the context data to be used when rendering a template. This does not necessarily involve ORM, so you could for example create a view that would not query any table in your DB, just gather some parameters from some other source and put them in a format suitable for use in the template.

  • get_queryset aims to create a% "core"% that may or may not be "refined" by the consumer code. That is, if you have some operation that you want to do to all query sets before they are used (in a past project I pre-filtered the templates based on a field ) you can do it in this method. What will be done with the result then depends on the case (in a QuerySet , it will end up being used also in a template, but other uses without involving templates would also be possible).

I do not have experience with generic views to think about their codes, but at first glance there is no problem with them, or anything that could be improved. Maybe it would be possible to use a single query to query the sale and its items instead of two queries as it is being done, but I'm not sure if it is possible and / or there would be any significant performance advantage. And the first example seems to me to fail if there is no sale with the primary key queried, are you treating this possibility in any way? (i.e. for the exception not to propagate and result in a ListView error)

    
18.06.2015 / 09:14