Search code examples
djangodjango-modelsdjango-migrations

How can I make Django create migration files for tables that aren't Django managed?


Background

I've got a Django app that I want to test. The Django app relies on database tables that were created by a different, non-Django app, but in the same database. Every time I try to run a test I get the following error:

django.db.utils.ProgrammingError: relation "mytable" does not exist

I'm thinking that this error is caused by the fact that the table was created manually and there are no migrations.

Question

Is there a way I can tell Django to build migration files based off of a database table that already exists?


Solution

  • There is a tool called inspectdb in Django for this exact scenario.

    This should do the trick:

    python manage.py inspectdb > models.py
    

    For reference:
    https://docs.djangoproject.com/en/3.2/howto/legacy-databases/