Shaurya Chaudhuri
Shaurya Chaudhuri

Reputation: 3842

Model Field added using custom SQL not detected by Django

I have added a field to my model. But I have added the field to the model in DB through a custom sql query(Alter Field). Now when I try to create other Migration files, Django creates migration for adding the field to that model in DB. How to make django not do this?

I needed to do modify the collation of the field before adding a reference to another field. Django Alter Field does Alter Table-Add Field,AlterTable-Add Reference While I wanted Alter Table-Add Field,Modify Field Collation,AlterTable-Add Reference. The custom sql query is written inside a migration file.

Upvotes: 1

Views: 798

Answers (2)

Matt Hardcastle
Matt Hardcastle

Reputation: 678

You can use RunSQL to create the field with the proper collation. When calling RunSQL use the state_operations argument to supply the state changes your SQL code made to keep Django up-to-date.

Here's an example from Django's documentation:

from django.db import migrations

class Migration(migrations.Migration):

    operations = [
        migrations.RunSQL(
            "ALTER TABLE musician ADD COLUMN name varchar(255) NOT NULL;",
            state_operations=[
                migrations.AddField(
                    'musician',
                    'name',
                    models.CharField(max_length=255),
                ),
            ],
        ),
    ]

Upvotes: 8

Renoc
Renoc

Reputation: 439

Let django create the migration that has creating that field as the only change. Then use the --fake flag to tell the database that migration has already been run.

./manage.py migrate --fake [app] [migration number]

This may cause problems if you're stepping through all your migrations at a later date or if you've written custom backwards code for your SQL migration.

Upvotes: 0

Related Questions