realnot realnot - 4 months ago 25
Python Question

How to merge/join two resultset/table in django?

I'm trying to display a list of employees that are part of the same company. So for example with the given URL localhost/app/company-slug/ I'd like to show a list of rows where there are the details of all three models:

| first_name | last_name | company-slug | employee_status | employee_type |

With this models, how I can retrieve this kind of data?

class Employee(models.Model):
company = models.ForeignKey(Company)


class EmployeeProfile(models.Model):
employee = models.OneToOneField(Employee)
# Base
first_name = models.CharField(max_length=31)
middle_name = models.CharField(max_length=31, null=True, blank=True)


class EmployeeJob(models.Model):
employee = models.OneToOneField(Employee)
# Employment status
employment_status = models.ForeignKey(EmploymentStatus, null=True, blank=True)
employment_type = models.ForeignKey(EmploymentType, null=True, blank=True)


Edit 1:



I didn't know was possible join tables within template tags. This is a working solution suggested by @Shang Wang

{% for employee in employees %}
<tr class="table-row clickable" data-href="{% url 'hrm:detail' company.slug employee.pk %}">
<td><strong>A</strong></td>
<td>{{ employee.employeeprofile.first_name }} {{ employee.employeeprofile.last_name }}</td>
<td>{{ employee.employeejob.employment_status }}</td>
<td>{{ employee.employeejob.employment_type }}</td>
<td>4</td>
</tr>
{% endfor %}

Answer

I assume you already had an object for company in current page, getting the employees is really easy:

employees = Employee.objects.filter(company=company)
for employee in employees:
    print employee.employeeprofile.first_name
    print employee.employeeprofile.last_name
    print employee.employeejob.employment_status
    print employee.employeejob.employee_type

Django doc about OneToOneField.

Comments