Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When we should use db_index=True in Django?

When we should define db_index=True on model fields?

I'm trying to optimize the application & wanted to learn more about db_index in which conditions we should use it?

The documentation says that using db_index=True on model fields is to faster the lookups with slightly disadvantages with storage and memory.

Should we use db_index=True only on those fields which has unique values like the primary field id? what happens if we enabled indexing for those fields which are not unique and contains repetitive data.

like image 978
Arbazz Hussain Avatar asked Jan 05 '20 00:01

Arbazz Hussain


Video Answer


1 Answers

I would say you should use db_index=True when you have a field that is unique for more useful lookups.

For example if you a table customers with records of many users they'll each have their own unique user_id. Each user_id would be unique and having to index this field to find that unique user is more often desirable than say their first_name or last_name. Actually this is also ok but since they're not unique you will get probably recieve multiple results from your queries and this might not be as useful as using an referencing their id.

Have a look here to learn more about indexing

like image 155
Benji Avatar answered Oct 11 '22 13:10

Benji