Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select from multiple tables in one query with Django?

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 every Employee in a table, with the Company next to it. Which is simple enough by calling employees = Employee.objects.all() and in the template loop trough it and calling {{employee.company.name}}.

The problem with this solutions is that it will be created a new query for each item in the loop. So for each Employee there will be one query to Company looking something like this:

SELECT `company`.`id`, `company`.`name`
FROM `company`
WHERE `company`.`id` = 1 # This will of course be the employee.company_id

Instead I wish to make this join initially in the same query getting the Employees. Something like this:

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 around to solve this(without raw sql)? Or should this behavior be ignored, cached and considered "optimized"?

like image 543
tdolsen Avatar asked Mar 11 '10 14:03

tdolsen


People also ask

Can we fetch data from multiple tables using one query?

From multiple tables To retrieve information from more than one table, you need to join those tables together. This can be done using JOIN methods, or you can use a second SELECT statement inside your main SELECT query—a subquery.

Which object is used to SELECT data from multiple tables?

Below statement could be used to get data from multiple tables, so, we need to use join to get data from multiple tables.

How do I query multiple tables in SQL?

The most common way to query multiple tables is with a simple SELECT expression. To integrate results from different tables, use the FROM clause to name more than one table. Here’s how it works in practice: Syntax: SELECT table1.column1,table1.column2,table2.column1,....

How do I compare two fields in a query in Django?

Django provides F expressions to allow such comparisons. Instances of F () act as a reference to a model field within a query. These references can then be used in query filters to compare the values of two different fields on the same model instance.

How do I write a SQL query in Django?

If you find yourself needing to write an SQL query that is too complex for Django’s database-mapper to handle, you can fall back on writing SQL by hand. Django has a couple of options for writing raw SQL queries; see Performing raw SQL queries. Finally, it’s important to note that the Django database layer is merely an interface to your database.

How do you create an object in a database in Django?

To represent database-table data in Python objects, Django uses an intuitive system: A model class represents a database table, and an instance of that class represents a particular record in the database table. To create an object, instantiate it using keyword arguments to the model class, then call save () to save it to the database.


2 Answers

Using select_related() will pre-populate the appropriate attributes:

Employee.objects.select_related()
like image 50
Ignacio Vazquez-Abrams Avatar answered Oct 27 '22 01:10

Ignacio Vazquez-Abrams


It is an old question, let me provide a new answer.

Actually, you can do this:

employees = Employee.objects.all().values('id','name','company__name')

then, Django will automatically lookup Company class and find the company name for you.

on the template page, use {{employees.company__name}} then it will display the company name correctly.

like image 26
Ken Avatar answered Oct 27 '22 01:10

Ken