英文:
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),
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论