Django数据库迁移问题

一、数据库迁移问题

【问题一】

1. >> python3 manage.py makemigrations
django.db.utils.InternalError: (1050, "Table 'django_admin_log' already exists")

2. 错误原因:在迁移文件0001中需要新建表django_admin_log,但是数据库中已存在一个原有的表

3. 解决方案:

(1) 将原有表删除即可: mysql>> drop table django_admin_log;

(2) 重新迁移数据库: >> python3 manage.py migrate

【问题二】

1. >> python3 manage.py makemigrations

ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.user', but app 'users' isn't installed

2. 错误原因:新迁移的文件与旧的迁移文件冲突的问题

3. 解决方案:

删除旧的迁移文件,生成新的迁移文件回滚即可

>> python3 manage.py makemigrations
>> python3 manage.py migrate --fake users zero
>> python3 manage.py migrate

【问题三】

1. >> python3 manage.py makemigrations

ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'user.user',but app 'user' doesn't provide model 'user'.

Django数据库迁移问题_第1张图片 报错信息

2. User实体类

class User(AbstractUser): # 继承AbstractUser
    nickname = models.CharField(max_length=30,null=True,verbose_name='昵称')
    phone = models.CharField(max_length=30,null=True,unique=True,verbose_name='手机号')
    gender = models.CharField(max_length=10,choices=GENDER,default='1',null=True,blank=True,verbose_name='性别')
    usertype = models.IntegerField(choices=USERTYPE,default=2,verbose_name='用户类型') # 1表示卖家,2表示买家
    is_delete = models.BooleanField(default=False,verbose_name='是否禁用用户')

    def __str__(self):
        return self.username

    class Meta:
        db_table = 'user_user' # 数据库表名

3. 错误原因:没有给继承自AbstractUser类的user实体类授权,需要在settings.py里配置

4. 解决方案:

(1) 在settings.py文件中添加user应用,并添加user授权

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'user',
]

AUTH_USER_MODEL = 'user.User' # 指定user的模型, 应用.模型

(2)  重新迁移数据库 

>> python3 manage.py makemigrations
>> python3 manage.py migrate

可以参考>> ValueError in Django when running the “python manage.py migrate” command

你可能感兴趣的:(Django,Django,数据库迁移)