5

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.

1

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

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?
Apparently Django does changing an implicit through table to an explicit one, turns out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.