在Django模型中重命名唯一字段并迁移

时间:2018-11-14 10:56:40

标签: python django django-models django-1.11

我有一个看起来像这样的模型:

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

然后我进一步研究构建的内容之后,意识到username字段的名称稍有不同是非常重要的,因此在该行中进行了更改:

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

并运行python manage.py makemigrations myapp

它要求我提供默认值,但是当我查看它创建的.py迁移时,不喜欢它所做的事情:

# -*- 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'),
        ),
    ]

它正在尝试创建一个新字段,我只希望它重命名现有字段。

Django的新手(使用1.11.4)有人知道如何解决此问题吗?

1 个答案:

答案 0 :(得分:1)

由于您将AbstractUser子类化,因此始终包含username字段,因此不必为迁移选择重命名。您将需要更改用户模型类,使其看起来像这样:

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.

https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#a-full-example上有完整的示例。

根据您的用例,您可能需要重新实现权限方法。参见PermissionsMixin