··
148
·
2024-08-17 16:03

Django change an existing field to foreign key

I have a Django model that used to look like this:

class Car(models.Model):
    manufacturer_id = models.IntegerField()

There is another model called Manufacturer that the id field refers to. However, I realized that it would be useful to use Django's built-in foreign key functionality, so I changed the model to this:

class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer)

This change appears to work fine immediately, queries work without errors, but when I try to run migrations, Django outputs the following:

- Remove field manufacturer_id from car
- Add field manufacturer to car

Doing this migration would clear all the existing relationships in the database, so I don't want to do that. I don't really want any migrations at all, since queries like Car.objects.get(manufacturer__name="Toyota") work fine. I would like a proper database foreign key constraint, but it's not a high priority.

So my question is this: Is there a way to make a migration or something else that allows me to convert an existing field to a foreign key? I cannot use --fake since I need to reliably work across dev, prod, and my coworkers' computers.


内容来源于 Stack Overflow, 遵循 CCBY-SA 4.0 许可协议进行翻译与使用。原文链接:Django change an existing field to foreign key

Share Favourite Flag

1 answer

你可以做数据迁移

  1. 添加新字段
  2. 执行数据迁移  https://docs.djangoproject.com/en/3.1/topics/migrations/#data-migrations
  3. 移除旧字段

我不是特别确定,可能还存在另一种解决办法,你可以先将字段重命名为你想要的名字,然后将该字段替换为新的类型(执行迁移)。

operations = [
        migrations.RenameField(
            model_name='car',
            old_name='manufacturer_id',
            new_name='manufacturer',
        ),
        migrations.AlterField(
            model_name='car',
            name='manufacturer',
            field=ForeignKey(blank=True, null=True,  
                  on_delete=django.db.models.deletion.CASCADE
            ),
    ]


Answer at 2024-08-17 16:22:42
Flag
Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved