简体   繁体   English

重命名 Django 主键

[英]Renaming Django primary key

I am trying to rename the primary key field of a Django model, but I get django.db.utils.ProgrammingError: column "new_name" of relation "my_app_mymodel" does not exist .我正在尝试重命名 Django model 的主键字段,但我得到django.db.utils.ProgrammingError: column "new_name" of relation "my_app_mymodel" does not exist

The model is something like this: model 是这样的:

from django.db import models as django_db_models

class MyModel(django_db_models.Model):
    old_name = django_db_fields.BigAutoField(
                   null=False,
                   primary_key=True,
                   auto_created=True,
                   unique=True,
               )

And the migrations is:迁移是:

# Generated by Django 3.2.6 on 2022-10-03 15:33

from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('my_app', '0007_previous_migration'),
    ]

    operations = [
        migrations.RenameField(
            model_name='mymodel',
            old_name='old_name',
            new_name='new_name',
        ),
    ]

Not sure what am I doing wrong.不知道我做错了什么。 Any ideas?有任何想法吗?

PS: I don't know if this is related but there are foreign keys from other tables to this one. PS:我不知道这是否相关,但是其他表中有外键指向这个表。

1 - rename the field in the model: 1 -重命名 model 中的字段:

from django.db import models as django_db_models
class MyModel(django_db_models.Model):
    new_name = django_db_fields.BigAutoField(
                   null=False,
                   primary_key=True,
                   auto_created=True,
                   unique=True,
               )

2- run python manage.py makemigrations (it will just create new migrations based on that change) 2-运行python manage.py makemigrations (它只会根据该更改创建新的迁移)

3- then Change the field's name: 3-然后更改字段名称:

operations = [
        migrations.RenameField(
            model_name='mymodel',
            old_name='old_name',
            new_name='new_name',
        ),

4 - run python manage.py migrate (it will rename the field and keep your data ) 4 -运行python manage.py migrate (它将重命名该字段并保留您的数据)

django.db.utils.ProgrammingError: column "new_name" of relation >"my_app_mymodel" does not exist

When you see the above error message, It means that you've not done the migration yet and you've only created the related migration file for this change.当你看到上面的错误信息时,说明你还没有做迁移,你只是为这个变化创建了相关的迁移文件。 However, you can do this with the following command and then this problem will be solved and you will no longer see this error:但是,您可以使用以下命令执行此操作,然后此问题将得到解决,您将不再看到此错误:

python manage.py migrate

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM