Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.8 inspectdb command doesn't see PostgreSQL views as per documentation

I have a Django 1.8 application with a PostgreSQL database. I run the django inspectdb from the command line to examine models for the views, but the views don't show up in the model output.

Here's the version output:

17:36 $ python well/manage.py --version
1.8.2

And here's what psql sees:

\dv
                List of relations
 Schema |             Name              | Type |  Owner  
--------+-------------------------------+------+---------
 public | hospitalizations_over_30_days | view | dwatson
 public | interval_30_days              | view | dwatson
(2 rows)

From the django 1.8.2 documentation:

New in Django 1.8:
A feature to inspect database views was added. In previous versions, only tables (not views) were inspected.

How can I get the PostgreSQL views to appear in the Django 1.8.2 inspectdb output?

like image 300
David Watson Avatar asked May 27 '15 21:05

David Watson


2 Answers

As of Django 1.10, you can simply name an individual view as a parameter to your inspectdb command:

python well/manage.py inspectdb hospitalizations_over_30_days

The default inspectdb will only output models.py for tables, but models for views can be generated individually by naming them.

In Django 2.1 and above, if you want inspectdb to generate models for all tables and views, use the inspectdb --include-views option, which I contributed to Django 2.1 as a result of this question!

python well/manage.py inspectdb --include-views

To generate models for both tables and views in Django 2.0 and below, you have to edit the Django source code. In Django 2.0, change line 57 in django/core/management/commands/inspectdb.py to:

tables_to_introspect = options['table'] or connection.introspection.table_names(cursor=cursor, include_views=True)

Beware that the generated models won't have fields with primary_key=True set, you will need to add primary keys manually.

like image 96
Brendan Quinn Avatar answered Sep 20 '22 04:09

Brendan Quinn


In recent releases, there is an option to include views by passing it to the command as follows (both tables and views will be inspected):

python manage.py inspectdb --include-views > my_models.py
like image 6
Ahmed Avatar answered Sep 24 '22 04:09

Ahmed