cardamom
cardamom

Reputation: 7421

rename unique field in django model and migrate

I had a model which looks like this:

from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    username = models.TextField(max_length=100, unique=True)
    # other fields

Then I realised after working further on what I am building, that it is quite important that the username field is slightly differently named, so made an alteration in that line:

    username_internal = models.TextField(max_length=100, unique=True)

and ran python manage.py makemigrations myapp.

It asked me for a default value, but when I look at the .py migration it created, don't like what it has done:

# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2018-11-14 10:49
from __future__ import unicode_literals

import django.contrib.auth.validators
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0002_user_internalid'),
    ]

    operations = [
        migrations.AddField(
            model_name='user',
            name='username_internal',
            field=models.TextField(default=5, max_length=100, unique=True),
            preserve_default=False,
        ),
        migrations.AlterField(
            model_name='user',
            name='username',
            field=models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username'),
        ),
    ]

It is trying to create a new field, I just want it to rename the existing field.

Am new to Django (using 1.11.4) Does anyone know how to fix this?

Upvotes: 0

Views: 905

Answers (1)

Max
Max

Reputation: 1195

Due to you subclassing AbstractUser it is always including the username field so isnt picking up the rename for the migrations. You will need to change your user model class to look something like this:

from django.contrib.auth.models import AbstractBaseUser

class User(AbstractBaseUser):

    username_internal = models.TextField(max_length=100, unique=True)
    ...

    USERNAME_FIELD = 'username_internal'

    ...

    # you will also need to the user manager `objects = UserManager()`
    # you may be able to import and use the existing user manager from `django.contrib.auth.models import UserManager` depending on your other fields.

A full example is available on https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#a-full-example.

You may need to re-implement permissions methods depending on your use case. See PermissionsMixin.

Upvotes: 1

Related Questions