colinjwebb
colinjwebb

Reputation: 4378

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.

Upvotes: 4

Views: 4832

Answers (4)

jensq
jensq

Reputation: 146

Starting in Django 1.10, the inspectdb command takes an optional list of tables on the command line that limits which tables will be inspected.

Upvotes: 0

Venkat Kotra
Venkat Kotra

Reputation: 10743

Following solution given by @pfctdayelise

For django 1.8 mysql backend

open django/db/backends/mysql/introspection.py and find function get_table_list:

def get_table_list(self, cursor):
    cursor.execute("SHOW FULL TABLES")
    return [TableInfo(row[0], {'BASE TABLE': 't', 'VIEW': 'v'}.get(row[1]))
            for row in cursor.fetchall()]

Replace it with something like

def get_table_list(self, cursor):
    names = [TableInfo('mytable1', 't')]
    return names

To decide whether the second argument to TableInfo is t or v, run the mysql query SHOW FULL TABLES and find out your table_type if it is a BASE_TABLE then second argument is t else v

Then run

python manage.py inspectdb > models.py

Upvotes: 0

ha22109
ha22109

Reputation: 8316

Do not use syncdb > models.py. It's not a good practice. Make your models manually and add managed=False to it. If you will not add it your all database tables can be deleted via single command. After creating your models then run the syncdb so that tables are linked.

Upvotes: 0

pfctdayelise
pfctdayelise

Reputation: 5285

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 :)

Upvotes: 7

Related Questions