M
M
Maxim Zubenko2018-10-06 12:39:09
Django
Maxim Zubenko, 2018-10-06 12:39:09

How in Django to get in the finished results, along with the main query from the table, additional information from another table?

The point is. I have clients. These are the users of the User model that are added to the clients group. To get them all and then display them in the template, there is such a view in views.py:

def clients_all_view(request):
    group = Group.objects.get(name='clients')
    list_clients = group.user_set.all().order_by('-id')

    context = {
        'title': 'Список всех клиентов',
        'personal': True,
        'clients': list_clients,
    }
    return render(request, 'personal/clients.html', context=context)

But these are the clients. And customers have orders. Orders are in the Order model and from it are associated with users by the following construction:
class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, )
    ...

In the clients.html template in the HTML table (which displays a list of all clients), I would really like to see the number of orders of these same clients.
Of course, I can loop through the whole list_clients in the view and add some value of the orders_qty type, but in this case there will be 30 additional calls to the database at a time (because the page is scheduled to issue 30 orders at a time, and now even more are shown ), but in my opinion this is somehow not entirely true (not at all true).
Is there some kind of cunning feint with the ears to
list_clients = group.user_set.all().order_by('-id')
something to add so that there is an additional call to the Orders model and the number of orders of each found user is selected from the database of this model, supplementing the total data of the entire list_clients list?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question