[Python] Display Employees of a Company in a Single Row (instead of Multiple Rows) in Django...

Discussão em 'Python' iniciado por Stack, Fevereiro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I’m working with Django models for a Company and Employee. Each company has multiple employees, and I want to display the names of employees in a single row for each company, rather than displaying each employee on a new row.

    Currently, I have the following setup:

    The Company model has a one-to-one relationship with Employee, which is causing each employee to be displayed in a separate row in the template. Models:

    class Employee(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    comment = models.TextField()

    def __str__(self):
    return f"{self.first_name} {self.last_name}"


    class Company(models.Model):
    name = models.CharField(max_length=100)
    employeename = models.OneToOneField(Employee, on_delete=models.CASCADE, null=True)


    Problem: I want to display employees for each company in the following format:

    Apple - [Jessica, Mathewo, Anthony]


    Instead of the current format, which displays employees like this:

    Apple - Jessica
    Apple - Mathewo
    Apple - Anthony


    What I’ve Tried: I’ve used Company.objects.values('name').annotate(total=Count('employeename')) to get the count of employees per company, but I’m still getting the employee names in separate rows in the template.

    {% for company in companies %}
    <tr>
    <td>{{ company.name }} <a href="{% url 'api:form_view' company.id %}">(Add Employee)</a></td>
    <td>{{ company.id }}</td>

    <td>{{ company.employeename }}</td>

    </tr>
    {% endfor %}


    What I Need Help With: How can I modify the query or template to display the employee names in a list (e.g., Apple - [Jessica, Mathewo, Anthony]) instead of separate rows? I want to ensure that the employees are grouped and displayed in a single row per company in the template. Explanation of the Expected Outcome: I would like to have a Company row with a list of all employee names displayed in a single cell. The company’s name should appear once, followed by a list of employee names in that company (as an array or comma-separated).

    Continue reading...

Compartilhe esta Página