如何在Django中更改外键字段时将数据保存到数据库中?

huangapple go评论69阅读模式
英文:

How to save data in DB when change field on foreign key? Django

问题

我有一个模型:

class Car(models.Model):
    brand_id = models.UUIDField()
    
class Brand(models.Model):
    name = models.CharField()

现在我的数据库包含每个Car对象的brand_id数据,如果我将其从UUIDField更改为ForeignKey,数据将会丢失。

如何在一次迁移中保存数据?

英文:

I have a model:

class Car(models.Model):
    brand_id = models.UUIDField()

class Brand(models.Model):
    name = models.CharField()

Now my db contains the data of brand_id for each Car object, if i change it from UUIDField to ForeignKey, the data will lost.

How can i save the data using one migration?

答案1

得分: 1

python manage.py makemigrations
python manage.py migrate

在数据库迁移文件中

from django.db import migrations

def update_something_foreign_key(apps, schema_editor):
    Model = apps.get_model('your_app_name', 'Model')
    Something = apps.get_model('your_app_name', 'Something')
    
    for model in Model.objects.all():
        something_id = model.something_id
        something = Something.objects.filter(id=something_id).first()
        if something:
            model.something = something
            model.save()

class Migration(migrations.Migration):

    dependencies = [
        ('your_app_name', 'previous_migration_name'),
    ]

    operations = [
        migrations.RunPython(update_something_foreign_key),
    ]
英文:

python manage.py makemigrations
python manage.py migrate

in the database migration file

from django.db import migrations

def update_something_foreign_key(apps, schema_editor):
Model = apps.get_model('your_app_name', 'Model')
Something = apps.get_model('your_app_name', 'Something')

for model in Model.objects.all():
    something_id = model.something_id
    something = Something.objects.filter(id=something_id).first()
    if something:
        model.something = something
        model.save()

class Migration(migrations.Migration):

dependencies = [
    ('your_app_name', 'previous_migration_name'),
]

operations = [
    migrations.RunPython(update_something_foreign_key),
]

huangapple
  • 本文由 发表于 2023年7月6日 21:50:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76629560.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定