Home > Enterprise >  django model user create index for first_name, last_name
django model user create index for first_name, last_name

Time:10-04

I use settings.AUTH_USER_MODEL as default user model

And I want to create index on

public.auth_user.first_name
public.auth_user.last_name

Are there any elegant way to create this indexes ?

CodePudding user response:

You can do this by specifying a different User model. By simply inheriting from the AbstractUser [Django-doc] and specifying the indexes:

# app_name/models.py

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    first_name = models.CharField(_('first name'), max_length=150, db_index=True, blank=True)
    last_name = models.CharField(_('last name'), max_length=150, db_index=True, blank=True)
    
    class Meta(AbstractUser.Meta):
        swappable = 'AUTH_USER_MODEL'

then you can specify the user model to refer to the User model in the app_name module:

# settings.py

# ⋮

AUTH_USER_MODEL = 'app_name.User'

# ⋮

CodePudding user response:

Bit ugly but still elegant way: Create raw SQL migration witch create index.

First

pip3 install django-migrate-sql-deux

Then

import migrate_sql.operations

from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):
    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('my_app', '0094_last_migration_name')
    ]
    operations = [
        migrate_sql.operations.CreateSQL(
            name='auth_user_first_name_idx',
            sql='create index auth_user_first_name_idx on auth_user (first_name)',
            reverse_sql='drop index auth_user_first_name_idx',
        ),
        migrate_sql.operations.CreateSQL(
            name='auth_user_last_name_idx',
            sql='create index auth_user_last_name_idx on auth_user (last_name)',
            reverse_sql='drop index auth_user_last_name_idx',
        ),
    ]
  • Related