I have two tables, one “Company” and one “Employee”:
class Company(models.Model): name = models.CharField(max_length=60) class Employee(models.Model): name = models.CharField(max_length=60) company = models.ForeignField(Company)
And I want to list each Employee in the table next to the Company. It is quite simple by calling employees = Employee.objects.all() and in the template loop through it and calling {{employee.company.name}} .
The problem with these solutions is that a new query will be created for each element of the loop. Therefore, for each Employee there will be one request to the company, looking something like this:
SELECT `company`.`id`, `company`.`name` FROM `company` WHERE `company`.`id` = 1
Instead, I want to make this connection initially in the same request, getting Workers. Something like that:
SELECT `employee`.`name` AS `name`, `company`.`name` AS `company_name` FROM `employee` INNER JOIN `company` ON `employee`.`company_id` = `company`.`id`
Is this possible with the Django QuerySet? If not, is there a way I can work with to solve this (without raw sql)? Or should this behavior be ignored, cached, and considered "optimized"?
python join django django-queryset
tdolsen
source share