开发者

Generate a few models from existing database in Django

开发者 https://www.devze.com 2022-12-25 07:24 出处:网络
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 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 eith开发者_运维技巧er.


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


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号