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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With