Create model for existing database table in django

Question:

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.

Asked By: Rushikesh Sabde

||

Answers:

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.

Answered By: Alasdair

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.

Answered By: Akhil S
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.