Difference between get_context_data and get_queryset and code improvement (Django)

Asked

Viewed 1,346 times

1

i wanted to know the difference between get_context_data and get_queryset.

And I would like to know your opinion about my codes.

What’s right and what’s wrong in them?

https://github.com/rg3915/vendas/blob/master/vendas_project/vendas/views.py#L121-L132

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

https://github.com/rg3915/vendas/blob/master/vendas_project/vendas/views.py#L74-L88

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 in these codes?

1 answer

3

These methods have totally different purposes:

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

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

I have no experience with views generic to opine on their codes, but at first glance there is no problem in them, nor anything that could be improved. Maybe it was possible to use a single query to consult the sale and its items instead of two darlings how it’s being done, but I’m not sure if it’s possible and/or would bring some significant performance advantage. And the first example seems to me to fail if there is no sale with the consulted primary key, are you treating this possibility in any way? (i.e. for the exception not to propagate and result in an error 500)

  • Thanks for the feedback @mgibsonbr

Browser other questions tagged

You are not signed in. Login or sign up in order to post.