Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

python - Django 1.11 - make column foreign key without deleting

Previously we made integer field like:

cart_id = models.IntegerField(_('cart_id'), null=True)

But now I want to make this field foreign key:

cart = models.ForeignKey(Cart, null=True, db_column='cart_id')

The problem is that in the migration it generates two operations for deleting field and creating new one:

    operations = [
        migrations.RemoveField(
            model_name='order',
            name='cart_id',
        ),
        migrations.AddField(
            model_name='order',
            name='cart',
            field=models.ForeignKey(db_column=b'cart_id', to='cart.Cart', null=True),
            preserve_default=True,
        ),
    ]

Is there any way to make it as alter field?

question from:https://stackoverflow.com/questions/65918565/django-1-11-make-column-foreign-key-without-deleting

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First add the ForeignKey. Set the default blank=True and run migrations.

Then run this code to fill the previous instances (python manage.py shell):

m = Order.objects.all()
for i in m:
    c = Cart.object.get(id=i.cart_id)
    i.cart = c
    i.save()

Once done check if the ForeignKey is filled in the admin. You can remove blank=True in ForeignKey it is a required field.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...