Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
When are Django Querysets executed in the view?

I read the Querysets Django docs regarding querysets being lazy, but still am a bit confused here.

So in my view, I set a queryset to a variable like so

players = Players.objects.filter(team=team)

Later on, I have a sorting mechanism that I can apply

sort = '-player_last_name'


if pts > 20:
    players = players.filter(pts__gte = pts).order_by(sort)
else:
    players = players.filter(pts__lte = pts).order_by(sort)

if ast < 5:
   players = players.filter(asts__lte = ast).order_by(sort)
else:
   players = players.filter(asts__gte = ast).order_by(sort)

context = {players: players)

return render(request, '2021-2022/allstars.html', context)

What I want to know is, when is the players queryset evaluated? is it when each page is rendered, or everytime I assign the queryset to a variable? Because if it's the former, then I can just apply the .order_by(sort) chain and the previous applications are redundant.

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

QuerySets are evaluated if you "consume" the queryset. You consume a queryset by enumerating over it, call .get(…), .exists(…), .aggregate(…) or .count(…), check the truthiness (for example with if myqueryset: or bool(queryset), or call len(…) over it, etc. As a rule of thumb, it gets evaluated if you perform an action on it such that the result is no longer a QuerySet.

If you enumerate over it, or you call len(…) the result is cached in the QuerySet, so calling it a second time, or enumerating over it after you have called len(…) will not make another trip to the database.

In this specific case, none of the QuerySets are evaluated before you make the call to the render(…) function. If in the template you for example use {% if players %}, or {% for players %}, {{ players|length }}, or {{ players.exists }}, then it will evaluate the queryset.

over 4 years ago · Santiago Trujillo Relatório

0

Django queries are designed to be "lazy" - that is. they don't run the database query until something requests actual data. Queries can be modified by the addition of filtering and other similar functions.

For example, the following code requests all TeamMember objects when the search string is 'all', but otherwise adds a filter to restrict names to those matching the given search.

    squad_list = TeamMember.objects(state__in={"Hired", "Joined", "Staff", "Recruiting"})
    if squadname != 'all':
        squad_list = squad_list(squad__icontains=squadname.lower())

When the squadlist query is finally executed it will retrieve the required record. Dopes this help?

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda