4

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.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Rushikesh Sabde
  • 1,376
  • 1
  • 8
  • 24
  • 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

2 Answers2

4

Django provides a utility to auto-generate models from an existing database via inspectdb command.

You can create models by introspecting an existing database by executing following command

python manage.py inspectdb

The above command will output all the models Django can create from the existing database to stdout. You can save this as a file by using standard Unix output redirection

python manage.py inspectdb > models.py # or pass the app_name.models.py if you want to generate them inside models.py file of specific app

The output file will be saved to your current directory. Move that file to the correct app and you have a good starting point for further customization.

you can refer https://docs.djangoproject.com/en/4.1/ref/django-admin/#django-admin-inspectdb for more information.

Akhil S
  • 955
  • 11
  • 16
2

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

class ExistingModel(models.Model):
    ...

    class Meta:
        db_table = 'existing_table'
        managed = False

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

Corentin S.
  • 5,750
  • 2
  • 17
  • 21
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • 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