Search code examples
djangodjango-modelsdjango-database

Generate a few models from existing database in Django


I know this exists

django-admin.py inspectdb > models.py

However, is there an easy way to limit it? Without manually deleting what I don't want.

I'm connecting to a database that has over one hundred tables, but I only want models of about 4 or 5. Is there an easy way to generate models from a few given tables?

They are quite big tables, so I don't fancy typing them all out either.


Solution

  • I just did this myself, also with Oracle. It's possible - but not pretty.

    Assuming you know the names of the tables you want -

    open django/db/backends/oracle/introspection.py. There is a function get_table_list:

    def get_table_list(self, cursor):
        "Returns a list of table names in the current database."
        cursor.execute("SELECT TABLE_NAME FROM USER_TABLES")
        return [row[0].lower() for row in cursor.fetchall()]
    

    Just replace it with something like

    def get_table_list(self, cursor):
        names = ['mytable1', 'mytable2', 'mytable3']
        return names
    

    Then run your inspectdb and it will be a lot more managable :)