Faster Django Queries
Django has general and well-known queries like which are mostly used, these are generally used for getting objects/records of a single database table
models.objects.all()
models.objects.filter()
models.objects.get()
If you want to join Django [when you want to join two database tables having a Foreign-key relation], then we generally fetch all objects/records from the database and run a For loop where every record is joined with its related table record.
Lets us see the number of queries fired in every case:
1. one query to fetch all the objects.
2. “ N ” queries for every record in for loop
TOTAL = N+1 Queries for a joining of two db tables.
Now let us see both cases using the normal method and select_related method:
Normal method:-
Here we have two models:
1.Employee model and
2. Department which is a foreign key in the employee model.
This is how a general query is used to get data that are inter-related to each other.
See the no: of queries fired to fetch all the data related to foreign-key and normal model is 5 for 4 records present in the database table.
Now we use select_related for the same data to obtain or even more data.
See the number of records fired below is only 1 wherein all the joins are done for all the 4 records present in the database table.
The queries fired are not python queries but SQL query.
This may seem simple as there are only 4 records. Imagine an ORDERS database table where every order has a USER foreign key. Let us say we have 900000 orders each having a foreign key, so to join them, we have to run 900000 + 1 SQL queries.
But by using select_realted it will be done in a single SQL query. which saves a lot of time.