Creating a model for one existing database table

I have an existing, working Django project. The database contains one table that isn’t currently represented as a Django model. I’d like to create a model for it. I could set the model’s Meta options like:

class MyModel(models.Model):
    # fields here

    class Meta:
        managed = False
        db_name = "existing_table_name"

which would mean makemigrations wouldn’t generate the table creation code.

BUT, I do want the table to be created if the project is set up on a fresh, empty database – like when tests are run. So I’d need a table-creating migration for that case.

I’ve thought about creating a model with its own, new, table, then creating a data migration to copy data from the existing to the new table, but this seems fiddly and I wonder if I’ve missed a simpler option?

I would suggest you don’t mark the model as managed = False but migration --fake apply the resulting migration in environments where the table already exists.

This should ensure that the table exists in all environment going forward.

Thanks charettes.

It’s slightly fiddlier than I’d like but I’m not sure that a non-fiddly solution would be possible!