1

I have a custom user model that takes in the following fields:

class MyUser(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=60, unique=True)
    email = models.EmailField(max_length=120, unique=True)
    full_name = models.CharField(max_length=50, blank=True)
    is_active = models.BooleanField(default=True)

I know username and email automatically adds a db_index because it is set to unique=True.

Does it make sense to add db_index=True for my full_name and is_active fields?

I have a search feature that checks if the regex matches the full_name. In my model managers, I also filter against is_active=True.

I would like to optimize querys, but don't want to add tables to my database if it isn't necessary.

Thank you!

2 Answers 2

0

Yes,just add db_index=True into your field like this

full_name = models.CharField(max_length=50, blank=True,db_index=True)

After you migrate it, your database will create a index for this filed.

Refer this: https://docs.djangoproject.com/en/1.9/ref/models/fields/#db-index

Field.db_index

If True, a database index will be created for this field.

Sign up to request clarification or add additional context in comments.

Comments

0

Whether the index is used for full_name if you search using a regex is doubtable. You want to make sure of that by looking at the output of the query planner (e.g. postgres: EXPLAIN ANALYZE select * from myuser where user=...;).

If it is not used (for example because the regex lower cases everything) then you have to create a different index. For example on the lower cased value or even a GIN index (for partial matches).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.