D
D
Dmitry S2016-09-26 10:22:30
Django
Dmitry S, 2016-09-26 10:22:30

How to calculate the number of id's from a related table?

Good afternoon!
It is impossible to understand the correctness of query_set.
There is a Managers table and a Magasines table. That is, each store has its own manager.
I would like to display a table with managers, in which the name of the manager will be indicated in the first column, and the number of stores under their management in the second.
The tables look like this:

сlass Magasines(models.Model):
  m_type = models.ForeignKey('MagasinesTypes', verbose_name='Тип')
  m_name = models.CharField(max_length=100, verbose_name='Название МО')
  m_manager = models.ForeignKey('Manager', null=True, blank=True, verbose_name='Менеджер')

class Manager(models.Model):
  manager_family = models.CharField(max_length=100, verbose_name='Фамилия')
  manager_name = models.CharField(max_length=100, verbose_name='Имя')
  manager_surname = models.CharField(max_length=100, null=True, blank=True, verbose_name='Отчество')

views.py
def ManagerView(request):
  manager = Manager.objects.all()
  manager_sum = Manager.objects.aggregate(Count('id'))
  cab_in_manager = Magasines.objects.annotate(Count('cab_manager_id'))
  # Сборка рендера
  rendering = {
    'manager': manager,
    'manager_sum': manager_sum,
    'cab_in_manager': cab_in_manager,
  }
  return render(request, 'manager.html', rendering)

and template:
<table class="table">
      <tr>
        <th>ФИО</th>
        <th>Кол-во управляемых магазинов</td>
      </tr>
      {% for i in manager %}
      <tr>
        <td>{{ i.manager_family }} {{ i.manager_name }} {{ i.manager_surname }}</td>
        <td>{{ cab_in_manager.cab_in_manager__count }}
        <!--
          {% if cab_in_manager.cab_manager_id == i.manager_id %}
            {{ cab_in_manager.id__count }}
          {% endif %}
        -->
        </td>
      </tr>
      {% endfor %}

Apparently I can not understand the simplest. Help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-09-26
@anderlan

Manager.objects.annotate(magasines_count=models.Count('magasines_set'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question