2

I have an old table in the database. And I want to create a model in Django application. After creating a model and I used migrate command then it created a new table with its own name.

Rushikesh Sabde
  • 948
  • 1
  • 5
  • 20
  • You can use `inspectdb` to generate a "sketch" model from a database table (https://docs.djangoproject.com/en/2.2/howto/legacy-databases/#auto-generate-the-models) But you probably will need to do some extra "scaffolding" yourself. – Willem Van Onsem Aug 19 '19 at 13:02

1 Answers1

2

You can specify the table name by setting table on the model's Meta class. Set managed = False to prevent Django from creating the table.

class ExistingModel(models.Model):
    ...

    class Meta:
        table = 'existing_table'
        managed = False

After making these changes, I would revert the previous migration, remove the migration file, then run makemigrations again.

Alasdair
  • 278,338
  • 51
  • 534
  • 489
  • What about if you only want to temporarily have the table unmanaged, for a single migration, and then you want it managed afterward? I am thinking of the situation where you have a pre-existing implicit m2m through table and later want to add an explict model for it. Can you mark it as managed=False, makemigrations, migrate, and then mark it as managed=True afterward? – kloddant Feb 18 '21 at 20:15
  • Apparently Django does changing an implicit through table to an explicit one, turns out. – kloddant Feb 18 '21 at 20:50