Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cb109/895413311b4f72303af13810157737a6 to your computer and use it in GitHub Desktop.
Save cb109/895413311b4f72303af13810157737a6 to your computer and use it in GitHub Desktop.
Partially unmanaged models in Django ORM aka ignore certain columns/fields

Partially ignore table fields on a Django model

There may come a day where your table includes a field that your Django app should ignore and not even be aware of, while other clients may still need to use that field in production through normal SQL commands. How to achieve this?

Removing a model field will give you a migration step like this:

        migrations.RemoveField(
            model_name="mymodel",
            name="my_field",
        ),

which will issue an ALTER TABLE ... DROP COLUMN ... and kill the column that we want to preserve.

One way to prevent that is to use:

class Meta:
    managed = False

but that turns off the sync between your database table and the model class entirely, which is bit too much.

Turns out there is an alternative by modifying the migration to tell the ORM some operation happened, but actually doing nothing in terms of SQL command execution (based on this article):

    migrations.RunSQL(
        sql=migrations.RunSQL.noop,
        reverse_sql=migrations.RunSQL.noop,
        state_operations=[
            migrations.RemoveField(
                model_name="mymodel",
                name="my_field",
            ),
        ],
    )

The SeparateDatabaseAndState is most likely an alternative way of specifying this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment