Create multiple models from an existing database in Django

I know it 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 connect to a database containing more than a hundred tables, but I only need models around 4 or 5. Is there an easy way to generate models from multiple tables?

These are pretty large tables, so I don’t want to type them either.

+4
source share
3 answers

I just did it myself, also with Oracle. It is possible - but not very.

Assuming you know the names of the tables you want -

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

 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 inspectdb and it will be much more manageable :)

+7
source

Do not use syncdb > models.py . This is not a good practice. Make your models manually and add managed=False to it. If you do not add it, all of your database tables can be deleted with a single command. After creating your models, run syncdb so that the tables are linked.

0
source

The next solution given by @pfctdayelise

For django 1.8 mysql backend

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

 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 if the second argument is TableInfo t or v , run the mysql query SHOW FULL TABLES and find out your table_type , if it's BASE_TABLE , then the second argument is t else v

Then run

 python manage.py inspectdb > models.py 
0
source

Source: https://habr.com/ru/post/1305585/


All Articles